开发者

circular class member pointer?

开发者 https://www.devze.com 2023-01-06 13:49 出处:网络
I am not sure if I can describe the problem, but I will try my best. Here is the situation: If I can want a class1 has a pointer as a member variable pointing to another class, class2. Meanwhile, I w

I am not sure if I can describe the problem, but I will try my best. Here is the situation:

If I can want a class1 has a pointer as a member variable pointing to another class, class2. Meanwhile, I want class2 also has a pointer as a member variable pointing to class1. Is that possible?

class Class1
{
private:
    Class2* classptr;
        ... ...
public:
        ... ...
};

class Class2
{
private:
    Class1* classptr;
        ... ...
pu开发者_运维问答blic:
        ... ...
};

It appears to me that none of Class1 and Class2 has been recognized as an identifier. I guess none of Class1 and Class2 is created. Correct me if I am wrong.


You need a forward declaration. Either:

class Class1
{
private:
    class Class2* classptr;
        ... ...
public:
        ... ...
};

or:

class Class2;

class Class1
{
private:
    Class2* classptr;
        ... ...
public:
        ... ...
};
0

精彩评论

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