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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With