【发布时间】:2017-06-11 02:45:58
【问题描述】:
我有这个简单的 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应该是x的一个元素,但是当我修改y时,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';
}
但是。有没有办法使用y 作为类型test 而不是p 作为类型test*?
【问题讨论】:
-
除此之外,复制构造函数为什么要清空列表?
-
我看到很多(真的没必要)
news,但没有看到deletes。如果你想让y影响x,那么你只需要一个引用,而不是新对象。
标签: c++ c++11 pointers return-by-reference