在运行这个程序时,只有第一对值输出看起来正确,其他的值都不正确。这是怎么回事?
#include <iostream>
#include <vector>
class a
{
public:
class b
{
public:
a* parent;
void test()
{
std::cout<<parent->value<<std::endl;
}
} b1;
unsigned long value;
a()
{
b1.parent = this;
value = 2;
}
void go()
{
value++;
b1.test();
}
};
int main()
{
{
a a1;
a1.go();
std::cout<<a1.value<<std::endl;
}
std::cout<<std::endl;
{
a a1; a1 = a();
a1.go();
std::cout<<a1.value<<std::endl;
}
std::cout<<std::endl;
{
std::vector<a> a1; a1.push_back(a());
a1.at(0).go();
std::cout<<a1.at(0).value<<std::endl;
}
return 0;
}发布于 2011-02-04 05:47:52
类型'a‘缺少复制ctor和赋值运算符。因此,在复制或指定对象时,您无法正确更新它们的b1.parent。相反,b1.parent值指向与其真正父对象不同的'a‘对象。
要查看此问题的实际效果,请在现有代码中使用以下代码:
void go() {
value++;
std::cout << (this == b1.parent ? "as expected\n" : "uh-oh\n");
b1.test();
}要修复它,请修改类a:
a() : b1 (this), value (2) {} // a change from your default ctor
a(a const &x) : b1 (this), value (x.value) {}
a& operator=(a const &x) {
value = x.value;
return *this;
}并修改类b(必须像上面那样使用ctor初始化器):
b(a *parent) : parent (parent) {}https://stackoverflow.com/questions/4892039
复制相似问题