C++ 错误:成员访问不完整类型:前向声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19962812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:17:27  来源:igfitidea点击:

error: member access into incomplete type : forward declaration of

c++forward-declaration

提问by LOLKFC

I have two classes in the same .cpp file:

我在同一个 .cpp 文件中有两个类:

// forward
class B;

class A?{       
   void doSomething(B * b) {
      b->add();
   }
};

class B {
   void add() {
      ...
   }
};

The forward does not work, I cannot compile.

转发不起作用,我无法编译。

I get this error:

我收到此错误:

error: member access into incomplete type 'B'
note: forward declaration of 'B'

I'm using clang compiler (clang-500.2.79).

我正在使用 clang 编译器 (clang-500.2.79)。

I don't want to use multiple files (.cpp and .hh), I'd like to code just on one .cpp.

我不想使用多个文件(.cpp 和 .hh),我只想在一个 .cpp 上编码。

I cannot write the class B before the class A.

我不能在 A 类之前写 B 类。

Do you have any idea of how to resolve my problem ?

你知道如何解决我的问题吗?

采纳答案by masoud

Move doSomethingdefinition outside of its class declaration and after Band also make addaccessible to Aby public-ing it or friend-ing it.

doSomething定义移到其类声明之外和之后,B并通过-ing it 或-ing it使其add可访问。Apublicfriend

class B;

class A
{
    void doSomething(B * b);
};

class B
{
public:
    void add() {}
};

void A::doSomething(B * b)
{
    b->add();
}

回答by Some programmer dude

You must have the definitionof class Bbefore you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

在使用类之前,您必须有类的定义B。否则编译器怎么会知道存在这样的函数B::add

Either define class Bbefore class A, or move the body of A::doSomethingto after class Bhave been defined, like

要么在 classB之前定义 class ,要么在 class定义之后A移动A::doSomethingto的主体B,例如

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}