[英]C++ structs Interdependency
您好,我在同一個Header文件中聲明了需要互相使用的結構。
struct A; // ignored by the compiler
struct B{
A _iNeedA; //Compiler error Here
};
struct A {
B _iNeedB;
};
這項工作正常
class A;
class B{
A _iNeedA;
};
class A {
B _iNeedB;
};
// everything is good
非常感謝你!
這行不通: A
包含B
包含A
包含B
包含…。 在哪里停下來?
您可以為循環依賴關系建模的所有方法是使用指針:
class A;
class B {
A* _iNeedA;
};
class A {
B* _iNeedB;
};
現在,這些類不再包含彼此,而只是相互引用。
此外,您還需要注意不能使用尚未定義的內容 :在上面的代碼中,在定義B
之前已聲明 A
因此,可以在B
聲明指向 A
指針 。 但是在定義它之前您還不能使用 A
我回答我自己的問題。
事實是我在做什么並不完全是我發布的內容,但我是同一回事,實際上我正在使用帶有參數的運算符。 這些操作符主體必須在我的結構聲明之后(在結構外部)定義,因為結構B尚不知道結構A成員...
我說它正在與類一起使用,因為對於類,我們通常使用CPP文件進行方法定義,這里我沒有將任何cpp文件用於結構中使用的方法
我本打算刪除這篇文章,但是你們太快了;),
這是一個例子
struct A;
struct B {
int member;
bool operator<(const A& right); //body not defined
};
struct A {
int member;
bool operator<(const B& right)
{
return this->member < B.member;
}
};
bool B::operator<(const A& right) //define the body here after struct A definition
{
return this->member < A.member;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.