[英]How to implement two structs that can access each other?
我寫的代碼:
struct A;
struct B;
struct A
{
int v;
int f(B b)
{
return b.v;
}
};
struct B
{
int v;
int f(A a)
{
return a.v;
}
};
編譯消息:
|In member function 'int A::f(B)':|
11|error: 'b' has incomplete type|
7|error: forward declaration of 'struct B'|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|
我知道,為什么代碼不正確,但我不知道如何實現兩個可以相互訪問的結構。 有什么優雅的方式嗎? 提前致謝。
如果要保留成員函數的完全相同的簽名,則必須推遲成員函數的定義,直到看到兩個類定義為止
// forward declarations
struct A;
struct B;
struct A
{
int v;
int f(B b); // works thanks to forward declaration
};
struct B
{
int v;
int f(A a);
};
int A::f(B b) { return b.v; } // full class definition of B has been seen
int B::f(A a) { return a.v; } // full class definition of A has been seen
您也可以使用const&
函數參數(當A
和B
很大時性能更好),但即使這樣,您也必須推遲函數定義,直到看到兩個類定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.