c++ - 如何从C++中的嵌套类调用变量

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

所以我的代码是这样的

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?

最佳答案

代码有很多问题,我会用代码注释来解释

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"

关于c++ - 如何从C++中的嵌套类调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33252865/

相关文章:

c# - 无参数构造函数

javascript - 访问对象内部的数组

C++ 使用非静态成员函数对 vector 进行排序

c++ - 如何将2个类分成单独的.h文件并正确设置它们

c++ - 使用 imread 读取目录中的所有图像文件

c++ - 如何绘制圆角窗口边框?

ruby-on-rails - 用一段独立的代码扩展 Ruby 类

java - 如果我的子类也有不同的方法怎么办?

javascript - 从对象(带属性)转换的数组返回 0 长度

java - JSONObject 解析字典对象