我想實現一個類的指針爲類成員和方法返回指針,但在編譯我得到「語法錯誤:缺少';'之前 '*'」和 「缺少類型說明符 - 假定爲int。注意:C++不支持默認int」 錯誤C++類的方法返回指針到用戶定義的類實例
下面的代碼:
Main.cpp的:
#include "AClass.h"
#include "BClass.h"
int main (int argc, const char* argv[])
{
AClass a;
BClass b;
return 0;
}
AClass.h:
#ifndef ACLASS_H
#define ACLASS_H
#include "BClass.h"
class AClass
{
public:
BClass* getB();
void setB (BClass* inst);
private:
BClass* b;
};
#endif
BClass.h:
#ifndef BCLASS_H
#define BCLASS_H
#include "AClass.h"
class BClass
{
public:
AClass* getA();
void setA (AClass* inst);
private:
AClass* a;
};
#endif
我還沒有充實OU t類與cpp文件,我得到一串錯誤: 如果我創建C++文件並定義一切,這些都沒有關係,這些錯誤仍然存在。
1>------ Build started: Project: memberUDFpointers, Configuration: Debug Win32 ------
1> Main.cpp
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(9): error C2143: syntax error : missing ';' before '*'
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(9): warning C4183: 'getA': missing return type; assumed to be a member function returning 'int'
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(10): error C2061: syntax error : identifier 'AClass'
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(12): error C2143: syntax error : missing ';' before '*'
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(12): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents\cpp projects\memberudfpointers\memberudfpointers\bclass.h(12): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我已經看了很多不同的帖子,但我仍然在這個問題上摸不着頭。 有人可以給我一個線索嗎?
你有圓形包容;在頭文件中使用前向聲明而不是'#include'。 – ildjarn 2012-03-14 22:41:37
循環依賴,前向聲明;這應該讓你開始。 – Nim 2012-03-14 22:42:25
[C++中的循環依賴]可能的重複(http://stackoverflow.com/questions/4018816/circular-dependency-in-c) – 2012-03-14 22:43:38