2008-11-28 54 views

回答

10

請參閱forward references上的此頁。我看不出前向引用與指針和其他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 { 
    // ... 
}; 

我覺得這是你問的指針和向前聲明打交道時。

+0

確定感謝ü,但我可以假設,有一個在thsi情況下 – 2008-11-28 16:57:24

7

我認爲「向前引用」關於指針指這樣的事:

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

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

指針聲明結構之前,它指向的定義。

編譯器可以逃脫這個,因爲指針存儲的地址,你不需要知道什麼是在該地址預留內存的指針。

5

正向引用是當你聲明一個類型但沒有定義它時。

它允許通過指針使用類型(或參考用於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); 

現在,當你實現這些功能,您將需要結構定義,所以你需要包括噗通在PlopUtils.cpp .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 ... 
} 
-5

正向引用允許C編譯器少做通行證和顯著降低編譯時間。大約20年前,當計算機速度較慢,編程者效率較低時,這可能很重要。

3

我認爲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 

帕斯卡有相同的概念。

2

添加到以前的答案。前向引用是強制性的典型情況是,struct foo包含指向結構條的指針,並且bar包含指向foo的指針(聲明之間的循環依賴關係)。發表在C此情況下,唯一的辦法是使用前向聲明,即:

struct foo; 

struct bar 
{ 
    struct foo *f; 
}; 

struct foo 
{ 
    struct bar *b; 
};