简体   繁体   English

无法使用外部类对象访问内部类成员

[英]Can't access inner class member with outer class object

#include <iostream>

class Outer
{
    int o;
public:
    void setOuter(int o)
    {
        this->o=o;
    }
    class Inner
    {
    public:
        int i;
        int retOuter(Outer *obj)
        {
            return obj->o;
        }
    };
};

int main(int argc, char **argv) {
    Outer::Inner obj;
    obj.i=20;
    std::cout<<"Inner i = "<<obj.i<<std::endl;

    Outer *obj1=new Outer;
    obj1->setOuter(40);
    std::cout<<"Outer o = "<<obj.retOuter(obj1)<<std::endl;

    obj1->Inner::i =50; //Access the inner class members by Outer class object!
}

Everything in the above code is fine apart from the last line. 上面代码中的所有内容都可以与最后一行分开。 Why I am not able to access the Inner class member with an Outer class object? 为什么我不能使用外部类对象访问内部类成员? Outer class object should have all the public member access of class Outer And how is the behavior when I create an Inner class object as it is contained by an Outer class! 外部类对象应该具有的所有的公共成员访问class Outer又是怎样当我创建一个内部类对象,因为它是由一个外部类包含的行为!

Inner is just a class defined at a different scope. Inner只是在不同范围内定义的类。 It's no different than saying 这跟说没什么两样

class Inner
{
public:
    int i;
    int retOuter(Outer *obj)
    {
        return obj->o;
    }
};

and then 接着

Inner::i =50

which obviously isn't possible because i isn't static . 这显然是不可能的,因为i不是static

Declaring an inner class doesn't automagically declare a member of that type for the outer class which you can access using that syntax. 声明内部类不会自动为外部类声明可以使用该语法访问的该类型的成员。

Now, something like: 现在,类似:

class Outer
{
    int o;
public:
    void setOuter(int o)
    {
        this->o=o;
    }
    class Inner
    {
    public:
        int i;
        int retOuter(Outer *obj)
        {
            return obj->o;
        }
    } innerMember;
    //    ^^^
    // declare a member
};

int main(int argc, char **argv) {
    Outer *obj1=new Outer;
    obj1->innerMember.i =50; //Access the inner class members by Outer class object!
}

would work. 会工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM