访问同级类实例的成员

时间:2018-10-04 14:40:51

标签: c++ oop

从Child2访问c1的正确方法是什么?

要获得一些上下文,假设Child1和Child2是文本框,Child2需要使用c1.member当前值进行决策。这只是一些伪代码,看起来会更加清晰:

class Parent
{
public:
    Parent()
    {

    }

    ~Parent()
    {

    }

    class Child1
    {
    private:
        int i;
    };

    class Child2
    {
        Child2()
        {
            // somehow access c1.i;
        }

    };

private:
    Child1 c1;
    Child2 c2;
};

1 个答案:

答案 0 :(得分:0)

在我对问题提出了有益的评论之后,这是一个理智的解决方案:

class Parent
{
public:
    class StepTwo;

    Parent():
        // we're initializing c2 here because it does not have a default
        // constructor.
        c2(c1)
    {

    }

    ~Parent()
    {

    }

    class Child1
    {
    private:
        int i;
        // Making Child2 a friend class, allows it to access access private
        // members of Child1.
        friend class Child2;
    };

    class Child2
    {
    public:
        Child2(Child1 &r_c1)
        {
            pC1 = &r_c1;

            // pC1 can access everything from Child1 with ease.
        }
    private:
        Child1* pC1;
    };

private:
    Child1 c1;
    Child2 c2;
};