什么是前进的参照在C关于指点?

我可以得到一个例子吗?

有帮助吗?

解决方案

看看这页 前向引用.我看不出如何向前引用的将是不同的指针和与其他PoD类型。

注意,你可以向前声明的类型,和声明的变量是指向那个类型:

struct MyStruct;
struct MyStruct *ptr;
struct MyStruct var;  // ILLEGAL
ptr->member;  // ILLEGAL

struct MyStruct {
    // ...
};

// Or:

typedef struct MyStruct MyStruct;
MyStruct *ptr;
MyStruct var;  // ILLEGAL
ptr->member;  // ILLEGAL

struct MyStruct {
    // ...
};

我觉得这是什么你要当处理指针和进《宣言》。

其他提示

我想“前方参照”相对于指针装置是这样的:

struct MyStruct *ptr; // this is a forward reference.

struct MyStruct
{
  struct MyStruct *next; // another forward reference - this is much more useful
  // some data members
};

该指针它指向被定义结构之前声明。

在编译器可以逃脱这个,因为指针店的地址,你不需要知道什么是在该地址预留内存的指针。

正向引用是在声明类型,但不定义它。

它允许使用由指针(或C ++引用)类型,但不能声明的变量。

这是一种方法,说的是某物存在

的编译器

说,你已经在定义的扑通结构的 Plop.h

struct Plop
{
   int n;
   float f;
};

现在你想添加一些实用功能,与该结构的工作原理。您创建另一个文件的 PlopUtils.h (假设你不能改变Plop.h):

struct Plop; // Instead of including Plop.h, just use a forward declaration to speed up compile time

void doSomething(Plop* plop);
void doNothing(Plop* plop);

现在,当你实现这些功能,您将需要结构定义,所以你需要包括Plop.h文件在 PlopUtils.cpp

#include "PlopUtils.h"
#include "Plop.h" // now we need to include the header in order to work with the type

void doSomething(Plop* plop)
{
   plop->n ...
}

void doNothing(Plop* plop);
{
   plop->f ...
}

我认为C编译器最初有一通,其中它没有符号表建筑物和语义分析在一起。因此,例如:

    ....
    ... foo(a,b) + 1 ... // assumes foo returns int
    ....

    double foo(double x, double y){ ... } // violates earlier assumption

要避免这种情况,你说:

    double foo(double x, double y); // this is the forward declaration

    ....
    ... foo(a,b) + 1 ... // correct assumptions made
    ....

    double foo(double x, double y){ ... } // this is the real declaration

帕斯卡具有相同的概念。

添加到以前的答案。其中前向参考是强制性的典型情况是,当一个结构foo的包含一个指向一个struct巴,和栏包含一个指针为foo(声明之间的循环依赖关系)。表达用C这种情况下,唯一的方法是使用一个前向声明,即:

struct foo;

struct bar
{
   struct foo *f;
};

struct foo
{
   struct bar *b;
};

转发引用允许C编译器至少做通行证和显著降低编译时间。这可能是很重要的大约20年前,当电脑是非常缓慢,而且标准者低效率的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top