I am writing a small c++ - program containing a similar structure to the following:
class A {
B * someObjects;
};
typedef A* APointer;
struct B{
APointer a;
int n;
}
Trying to compile this gives a "identifier is undefined" error since struct B is not known inside class A. Otherwise declaring struct B before class A should still give a similar error, since then B does not know APointer, or APointer does not know A. Is there any possibility to make class A and struct B being good friends? Thanks in advance!
You need to forward declare B
as the compiler has no idea what B
is when it is used in A
. B
is considered an incomplete type in A
and you are allowed to have a pointer or reference to B
in A
. You can change your code to:
struct B;
class A {
B * someObjects;
};
typedef A* APointer;
struct B{
APointer a;
int n;
};
Have you ever heard the term Forward Declaration ! Your compiler don't know about B
yet. So give a declaration of B
first.
struct B; // forward declaration
class A {
B * someObjects;
};
//... rest of the code
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.