c++ 正确的方法来向前声明结构?[重复]

ny6fqffe  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(130)

此问题在此处已有答案

Resolve build errors due to circular dependency amongst classes(12个答案)
C++ class declaration after using it(3个答案)
5天前关闭。
假设我想声明结构AB

  1. struct A{
  2. B toB(){
  3. return B();
  4. }
  5. };
  6. struct B{
  7. A toA(){
  8. return A();
  9. }
  10. };

字符串
我会得到一个错误,类型B是未定义的

  1. main.cpp:2:2: error: unknown type name 'B'


如何正确声明B
执行以下操作

  1. struct B;
  2. struct A{
  3. B toB(){
  4. return B();
  5. }
  6. };
  7. struct B{
  8. A toA(){
  9. return A();
  10. }
  11. };


导致

  1. main.cpp:4:4: error: incomplete result type 'B' in function definition
  2. main.cpp:1:8: note: forward declaration of 'B'
  3. main.cpp:5:10: error: invalid use of incomplete type 'B'
  4. main.cpp:1:8: note: forward declaration of 'B'

nafvub8i

nafvub8i1#

问题不在于forward声明,问题在于你试图在它的定义之前使用B。forward声明只告诉编译器,在你的例子中,有一个名为B的结构,它没有定义它。
你可以把方法的定义从类中分离出来,就像这样:

  1. struct B;
  2. struct A{
  3. B toB(); // B is not defined yet
  4. };
  5. struct B{
  6. A toA(){
  7. return A();
  8. }
  9. };
  10. B A::toB() { // Now that B is defined, you can use it
  11. return B();
  12. }

字符串

展开查看全部

相关问题