2012-04-08 128 views
0

對於controling結構成員和力量程序員使用的getter/setter函數,我想寫這樣的代碼如下模式:如何在頭文件中定義並使用沒有完整結構定義的結構體?

/* Header file: point.h */ 
... 
/* define a struct without full struct definition. */ 
struct point; 

/* getter/setter functions. */ 
int point_get_x(const struct point* pt); 
void point_set_x(struct point* pt, int x); 
... 

//-------------------------------------------- 

/* Source file: point.c */ 
struct point 
{ 
    int x, y; 
}; 

int point_get_x(const struct point* pt) {return pt->x; } 

void point_set_x(struct point* pt, int x) {pt->x = x;} 

//-------------------------------------------- 

/* Any source file: eg. main.c */ 

#include "point.h" 
int main() 
{ 
    struct point pt; 

    // Good: cannot access struct members directly. 
    // He/She should use getter/setter functions. 
    //pt.x = 0; 

    point_set_x(&pt, 0); 
} 

但是這個代碼不MSVC++ 2010

這改變編譯我應該做編譯?

注意:我使用ANSI-C(C89)標準,不是C99或C++。

回答

4

在point.c中創建一個make_point函數來創建點; main.c不知道結構有多大。

而且

typedef struct point point; 

將支持聲明使用point而非struct point

3
point pt; 

該類型的名稱是struct point。你必須每次都使用整件事情,否則你需要typedef它。 *

I.e.你應該寫

struct point pt; 

那裏在main


你可能會從標準庫的思維FILE*之類的東西,並希望複製這種行爲。要做到這一點使用

struct s_point 
typedef struct s_point point; 

在標題。 (有很短的寫法,但我想避免混淆。)這將聲明一個名爲struct s_point的類型併爲其分配一個別名point


(*)注意,這不同於C++,其中struct point聲明瞭一個名爲point型這是一種struct

+0

你說得對,我忘了:)。但另一個錯誤顯示:'錯誤C2079:'pt'使用未定義的結構'point'' – 2012-04-08 21:41:38

+0

請參閱Doug的回答:'main'不知道'point'有多大,所以你想要一個'point * '有一個從庫代碼獲得分配。 – dmckee 2012-04-08 21:43:47