に動的なオブジェクトのリストを作成することができ、私はアイデアは、ネストされたリストのリストを作成することであるC++はどのように私は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';
}
に、この単純なプログラムを持っています。 y
は私はy
を変更する場合しかし、その後x
が変更されない、x
の要素であると考えられます。
所望の出力は次のようになります。
[three,[four]]
[one,[two],[three,[four]]]
が、私は
[three,[four]]
[one,[two],[three]]
を取得し、私はおそらくtest::add
にポインタを返すと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';
}
しかし、 。タイプtest
ではなく、タイプtest*
としてp
としてy
使用する方法はありますか?
コピーコンストラクタがリストをクリアするのはなぜですか? –
私はたくさんの(本当に不必要な) '新しい'を見ますが、 '削除'はありません。 'y'が' x'に影響を与えたいのであれば、必要なのは新しいオブジェクトではなく参照だけです。 – chris