简体   繁体   中英

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.

#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.

Just need to delay the definitions of both test methods until both classes are defined:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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