c++ - 地方类(Class) c-ism

标签 c++

只有第一对运行该程序时输出的值看起来是正确的,其他的则不正确。这是怎么回事?

#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;
}

最佳答案

您缺少类型“a”的复制构造函数和赋值运算符。当复制或分配对象时,您因此没有正确更新它们的 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) {}

关于c++ - 地方类(Class) c-ism,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892039/

相关文章:

c++ - C++ 中的特定模板友元

c++ - 将对话框控件移动到选项卡中?

c++ - 用 C++ 编写方法/函数的四种相同方法?

c++ - 错误 LNK2019 : unresolved external symbol

c++ - C++ 复制构造函数上的双重释放错误

c++ - 使用 shared_ptr<void> 初始化结构

c++ - 当我输入密码时,第一个字母与我输入的不同

c++ - 错误 : expected primary-expression before ‘double’ fix?

c++ - Direct2D - 保留现有内容并覆盖新值

c++ - OpenGL三角形邻接计算