C ++嵌套类驱动我疯狂 [英] C++ Nested classes driving me crazy

查看:94
本文介绍了C ++嵌套类驱动我疯狂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编译这个非常简单的代码片

i am trying to compile this very simple piece of code

class myList
{
public:
    std::vector<std::string> vec;
    class Items
    {
    public:
        void Add(std::string str)
        {
            myList::vec.push_back(str);
        };
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}

我可以做什么来使这项工作没有创建更多的对象需要或过度复杂

what can i do to make this work without creating more objects that needed or overcomplicating stuff...

推荐答案

添加几个构造函数和一个指向父类的指针。

Add a couple of constructors and a pointer to the parent class.

#include <string>
#include <vector>
class myList
{
public:
    std::vector<std::string> vec;
    myList(): items(this) {} // Added
    class Items
    {
    public:
        Items(myList *ml): self(ml) {}  // Added
        void Add(std::string str)
        {
                self->vec.push_back(str); // Changed
        };
        myList *self; //Added
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}



您需要myList()构造函数,内部类成员变量的实例。然后你需要Items构造函数来存储指向外部myList类实例的指针。最后,在Add方法中,您需要在存储的myList实例中引用vec。

You need the myList() constructor, so it registers instances of itself with the instance of the inner class member variable. Then you need the Items constructor to store the pointer to the outer myList class instance. Finally in the Add method, you need to reference vec in the stored myList instance.

正如Catskul指出的,Item构造函数不能使用myList指针它接收。我也想说,虽然这个答案更接近原来的意图,steveth45的答案更接近你想在一个真正的程序中做的。

As Catskul points out, the Item constructor mustn't actually do anything with the myList pointer it receives. I'd also like to say that though this answer is closer to the original intent, steveth45's answer is closer to what you would want to do in a real program.

这篇关于C ++嵌套类驱动我疯狂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆