简体   繁体   English

c ++两个类互相引用错误:'ClassName'之前的预期类型说明符

[英]c++ two class reference each other Error: expected type-specifier before 'ClassName'

i write two class in a header file, like below, and the two class reference each other, and i add class B before use in A class, but it has a error. 我在头文件中写了两个类,如下所示,两个类相互引用,我在A类中使用之前添加了B类,但它有一个错误。

#ifndef TEST_H
#define TEST_H
class B;
class A {
public:
    B *b;
    void test() {
        b = new B();
    }
};

class B {
public:
    A *a;
    void test() {
        a = new A();
    }
};

#endif // TEST_H

error message image 错误消息图像

how to solve it? 怎么解决? Thank you. 谢谢。

b = new B();

At this point, the forward declaration is no longer sufficient. 此时,前方声明已不再适用。 The definition of class B must be known in order to instantiate an instance of the class. 必须知道类B的定义才能实例化类的实例。

Just need to delay the definitions of both test methods until both classes are defined: 只需要延迟两个test方法的定义,直到定义了两个类:

class B;
class A {
public:
    B *b;
    void test();
};

class B {
public:
    A *a;
    void test();
};

inline void A::test() {
    b = new B();
}

inline void B::test() {
    a = new A();
}

Well, technically, it's not necessary to relocate the definitions of both class's test() methods, but it looks neater this way. 从技术上讲,没有必要重新定位类的test()方法的定义,但它看起来更整洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM