mercredi 25 janvier 2017

How can I create a list of dynamic objects in C++

I have this simple program in C++

#include <iostream>
#include <string>
#include <list>
using namespace std;

class test {
    private:
        string _name;
        list<test*> _list;
    public:
        test(const string& S): _name(S) { this->_list.clear(); }

        const string& to_string() {
            string*sp = new string("[");
            *sp += this->_name;
            for(test*tp: this->_list) {
                *sp += ",";
                *sp += tp->to_string();
            }
            *sp += "]";
            return *sp;
        }

        test& add(const string& S) {
            test*tp = new test(S);
            this->_list.push_back(tp);
            return *tp;
        }
};

int main() {
    test x("one");
    x.add("two");
    test y = x.add("three");
    y.add("four");
    cout << y.to_string() << '\n';
    cout << x.to_string() << '\n';
}

The idea is to create a list of nested lists. y is supposed to be an element of x, however when I modify y, then x is not modified.

The desired output is:

[three,[four]]
[one,[two],[three,[four]]]

but I get

[three,[four]]
[one,[two],[three]]

I can probably solve the problem by returning a pointer in test::add and modifying main:

int main() {
    test x("one");
    x.add("two");
    test*p = x.add("three");
    p->add("four");
    cout << y->to_string() << '\n';
    cout << x.to_string() << '\n';
}

However. Is there a way to use y as type test rather than p as type test*?

Aucun commentaire:

Enregistrer un commentaire