2016-11-22 456 views
1

我有以下文件結構包含一個結構的封裝類型的定義,當我嘗試訪問結構的成員,我得到Member access into incomplete type錯誤。問題是什麼?成員訪問到不完整類型錯誤

foo_encoder.c

#include "foo.h" 
//... 
struct FooEncoder { 
    int A; 
    int B; 
    foo_int32 C; 
    //... 
} 

foo.h中

extern "C" { 
    typedef struct FooEncoder FooEncoder; 
    //... 
} 

foo_interface.h

typedef struct MyFooEncInst FooEncInst; 

foo_interface.cc

#include "foo_interface.h" 
#include "foo.h" 
//... 
struct MyFooEncInst { 
    FooEncoder* encoder; 
}; 
//... 
MyFoo_Encode(FooEncInst* inst,...) { 
//... 
    if (d > inst->encoder->C) { // This is where I get the error 
//... 
} 

foo_int32在另一個地方所定義。

+0

將foo_encoder.c包含到代碼中,它將起作用。之後讓我知道,並會給出完整的答案。另一種方法是在新的.h文件中對struct FooEncoder進行全面定義幷包含它。 – Nick

+0

您正嘗試訪問「MyFooInst *」類型變量的成員。但是,在您提供的代碼中沒有「MyFooInst」類型的定義。 – sigy

回答

1

您正在請求FooEncoder結構中的成員,該結構在您的foo_interface.cc文件中的任何地方都不可見。這看起來類似於pimpl idiom

爲了讓你的代碼知道FooEncoder的結構,你需要或者

#include "foo_encoder.c" 
foo_interface.cc文件

(我挺不喜歡這個解決方案,你沒有張貼完整的代碼)或者將頭文件中的結構定義移動到其他地方幷包含該頭文件(推薦)。

2

foo.h正在向僅在foo.c中定義的結構聲明類型定義,因此foo_interface.cc對FooEncoder的實際內容沒有可見性。您可以通過將foo_encoder.c中的結構定義移動到foo.h來解決此問題。

0

您嘗試訪問的類型僅在您嘗試訪問時才提前聲明。你可以看看這個question to learn what a forward declaration is,而answers to this questions解釋什麼時候你可以使用前向聲明,什麼時候你不能。

您的typedef foo.h基本上充當FooEncoder類型的前向聲明。您將文件包含在foo_interface.cc中。因此,編譯器知道,類型存在,但它不知道其內部的任何內容,例如它具有的成員。因此它不知道是否有成員C就像您請求訪問。 您需要告訴編譯器如何MyFooEncInstFooEncoder看起來像內部它能夠訪問任何成員。

相關問題