转发声明结构的正确方法? [重复]

问题描述 投票:0回答:1

假设我想声明结构体

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'
c++ struct forward-declaration
1个回答
0
投票

问题不在于前向声明,问题在于您尝试在其定义之前使用

B
。前向声明仅告诉编译器在您的情况下有一个名为
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();
}
© www.soinside.com 2019 - 2024. All rights reserved.