开发者

Is there some way to create a class that have an object of a class that have an object of this class in C++?

开发者 https://www.devze.com 2023-04-08 17:47 出处:网络
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?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消