此问题在此处已有答案:
Resolve build errors due to circular dependency amongst classes(12个答案)
C++ class declaration after using it(3个答案)
5天前关闭。
假设我想声明结构A
和B
struct A{
B toB(){
return B();
}
};
struct B{
A toA(){
return A();
}
};
字符串
我会得到一个错误,类型B
是未定义的
main.cpp:2:2: error: unknown type name 'B'
型
如何正确声明B
?
执行以下操作
struct B;
struct A{
B toB(){
return B();
}
};
struct B{
A toA(){
return A();
}
};
型
导致
main.cpp:4:4: error: incomplete result type 'B' in function definition
main.cpp:1:8: note: forward declaration of 'B'
main.cpp:5:10: error: invalid use of incomplete type 'B'
main.cpp:1:8: note: forward declaration of 'B'
型
1条答案
按热度按时间nafvub8i1#
问题不在于forward声明,问题在于你试图在它的定义之前使用
B
。forward声明只告诉编译器,在你的例子中,有一个名为B
的结构,它没有定义它。你可以把方法的定义从类中分离出来,就像这样:
字符串