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

ny6fqffe  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(88)

此问题在此处已有答案

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

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'

nafvub8i

nafvub8i1#

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

struct B;

struct A{
  B toB(); // B is not defined yet
};

struct B{
  A toA(){
    return A();
  }
};

B A::toB() { // Now that B is defined, you can use it
    return B();
}

字符串

相关问题