Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 611
jecyhw Avatar asked Feb 19 '26 05:02

jecyhw


1 Answers

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.

like image 116
Sam Varshavchik Avatar answered Feb 21 '26 21:02

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!