访问封闭类的受保护成员[嵌套类]

时间:2021-11-01 23:29:15

I got the following code:

我得到以下代码:

class enclosing{
protected:
    int var1 = 2;
    int var2 = 4;
public:
    class problem{
    friend enclosing;
    public:
        void DoStuff(enclosing&e1){
            int Sum = e1.var1 + e1.var2;
        }
    }i1;
}e1;

My question is, how do i access the protected member variables of the enclosing class? Is this even Legal?

我的问题是,如何访问封闭类的受保护成员变量?这甚至是合法的吗?

2 个解决方案

#1


You have your friendship backwards - a class can't declare itself to be friend of somebody else.

你有你的友谊倒退 - 一个班级不能宣称自己是别人的朋友。

Unlike in Java's "inner classes", a class defined within a class does not automatically have access to an instance of the class the defines it - the "inner" class is completely independent, and you need to pass it the instance you want it to work with.

与Java的“内部类”不同,类中定义的类不会自动访问定义它的类的实例 - “内部”类是完全独立的,您需要将它想要的实例传递给它与...合作。

Like so:

class enclosing
{
protected:
    int var1 = 2;
    int var2 = 4;
public:
    friend class problem;
    class problem
    {
    public:
        void DoStuff(enclosing& e){
            int Sum = e.var1 + e.var2;
        }
    } i1;
} e1;

int main()
{
    e1.i1.DoStuff(e1);
    enclosing e2;
    e2.i1.DoStuff(e1); // Also works
    enclosing::problem x;
    x.DoStuff(e2); // This, too.
}

#2


The data members have to be accessed via an object of the enclosing class. For example

必须通过封闭类的对象访问数据成员。例如

void DoStuff( const enclosing &e){
            int Sum = e.var1 + e.var2;
        }

#1


You have your friendship backwards - a class can't declare itself to be friend of somebody else.

你有你的友谊倒退 - 一个班级不能宣称自己是别人的朋友。

Unlike in Java's "inner classes", a class defined within a class does not automatically have access to an instance of the class the defines it - the "inner" class is completely independent, and you need to pass it the instance you want it to work with.

与Java的“内部类”不同,类中定义的类不会自动访问定义它的类的实例 - “内部”类是完全独立的,您需要将它想要的实例传递给它与...合作。

Like so:

class enclosing
{
protected:
    int var1 = 2;
    int var2 = 4;
public:
    friend class problem;
    class problem
    {
    public:
        void DoStuff(enclosing& e){
            int Sum = e.var1 + e.var2;
        }
    } i1;
} e1;

int main()
{
    e1.i1.DoStuff(e1);
    enclosing e2;
    e2.i1.DoStuff(e1); // Also works
    enclosing::problem x;
    x.DoStuff(e2); // This, too.
}

#2


The data members have to be accessed via an object of the enclosing class. For example

必须通过封闭类的对象访问数据成员。例如

void DoStuff( const enclosing &e){
            int Sum = e.var1 + e.var2;
        }