Can't access inner class member with outer class object

后端 未结 1 1542
误落风尘
误落风尘 2021-01-29 04:05
#include 

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


        
相关标签:
1条回答
  • 2021-01-29 04:39

    Inner is just a class defined at a different scope. 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.

    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.

    0 讨论(0)
提交回复
热议问题