In C++, is there some way to create a class that have, as attribute, an object of a class that have, as attribute, 开发者_如何学编程an object of the first class?
e.g.:
class A {
B attribute;
public:
A(){}
};
class B {
A attribute;
public:
B(){}
};
The code above does not compile. Is there some way to do something alike?
Thanks!
First, you need to forward declare your class B. If not, the compiler wouldn't know what the B is. Also, change the attributes to be pointers, or else you will still have a compiler error, even though you forward declared B, it still doesn't know the implementation yet!
The following code may help, good luck...
class B;
class A {
B *attribute;
public:
A(){}
};
class B {
A *attribute;
public:
B(){}
};
These definitions, even if you could use forward declaration to make them work (which you can't), are inherently recursive. An A contains a B, which contains an A, which contains a B, and on and on. It is nonsensical.
You need to rethink your structure. You're trying to define a structure that contains another structure, which contains the first structure which contains the second structure, etc...
精彩评论