【问题标题】:how to call variable from a nested class in C++如何从 C++ 中的嵌套类调用变量
【发布时间】:2016-01-20 01:40:19
【问题描述】:

所以我的代码是这样的

class foo1
{
    public:
        foo1()
        {
            a = "text";
        }

        void getString()
        {
            return a;
        }
    private:
        string a;
};

class foo2
{
    public:
        foo2()
        {
            foo3 boo3;
        }
        class foo3
        {
            public:
                foo3()
                {
                    foo1 boo1;
                }
            private:
                foo1 boo1;
        };
    private:
};

int main()
{
    foo2 object;
    cout << /* ??? */ ;
}

首先,类中的代码结构是否有任何问题,其次,我应该在注释的位置放置什么来显示我在 int main() 中初始化的 foo2 对象中的字符串 a?

【问题讨论】:

标签: c++ class object c++11 nested-class


【解决方案1】:

代码有多个问题,我用代码cmets解释一下

class foo1
{
    public:
        //use initializer lists to avoid extra copying
        foo1() : a("text") 
        {
        }

        //change return type from void to a const reference to string
        const string & getString()
        {
            return a;
        }
    private:
        string a;
};

class foo2
{
    public:
        //use initializer lists to avoid extra copying
        foo2() : boo3() 
        {
        }
        class foo3
        {
            public:
                //use initializer lists to avoid extra copying
                foo3() : boo1()
                {
                }

                //you need a function that will allow access to the private member. Returning a const reference avoids extra copying
                const foo1 & boo()
                {
                    return boo1;
                }

            private:
                foo1 boo1;
        };

        //you need a function that will allow access to the private member
        const foo3 & foo()
        {
            return boo3;
        }
    //you need to save the foo3 object in the class to be able to use it later
    private:
        foo3 boo3;
};

int main()
{
    foo2 object;
    cout << object.foo().boo().getString();
}

现在这是您访问字符串的方式:

    cout << object.foo().boo().getString();
            \__________/ \___/ \_________/
                 ^         ^        ^---- get the string from the foo1 object
                 |         |---- get the foo1 object from the foo3 object
                 |---- get the foo3 object stored in "object"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2019-08-10
    • 2015-04-17
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多