我写的代码:
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
较大时性能更好),但即使那样您也必须推迟函数定义,直到看到两个类定义。
关于c++ - 如何实现两个可以相互访问的结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16210569/