什么是C的前向参考?
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中定义了Plop结构:
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);
现在,当您实现这些function时,您将需要结构定义,因此您需要在PlopUtils.cpp中包含Plop.h文件:
#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
帕斯卡有着相同的概念。
添加到以前的答案。 前向引用是必需的典型情况是struct foo包含指向结构栏的指针,而bar包含指向foo的指针(声明之间的循环依赖)。 在C中表达这种情况的唯一方法是使用前向声明,即:
struct foo; struct bar { struct foo *f; }; struct foo { struct bar *b; };
前向引用允许C编译器执行较少的传递并显着减少编译时间。 大约20年前,当计算机速度慢得多且编制效率低下时,这可能很重要。