gpt4 book ai didi

c++ - 不同构造函数中的构造函数调用产生错误数据

转载 作者:太空狗 更新时间:2023-10-29 19:53:08 26 4
gpt4 key购买 nike

以下是复制我的问题的最小程序:

#include <iostream>

using namespace std;

class Test
{
public:
Test()
{
_a = 0;
}
Test(int t)
{
Test();
_b = t;
}
void Display()
{
cout << _a << ' ' << _b << endl;
}
private:
int _a;
int _b;
};

int main()
{
Test test(10);
test.Display(); // 70 10

return 0;
}

当我这样做时,_a 被垃圾初始化。为什么会这样?从另一个构造函数中调用构造函数时会出现问题吗?

最佳答案

这里的问题是在这段代码中:

Test(int t)
{
Test();
_b = t;
}

调用默认的Test构造函数,然后设置_b = t。相反,它使用默认构造函数创建类型为 Test 的临时对象,忽略该临时对象,然后设置 _b = t。因此,默认构造函数不会为接收者对象运行,因此 _a 将保持未初始化状态。

要解决这个问题,在 C++11 中,您可以编写

Test(int t) : Test() {
_b = t;
}

它会调用默认构造函数,或者(在 C++03 中)您可以将默认构造函数中的初始化代码提取到您从默认构造函数和参数化构造函数中调用的辅助成员函数中:

Test() {
defaultInit();
}
Test(int t) {
defaultInit();
_b = t;
}

或者,如果您有 C++11 编译器,只需使用默认初始化器消除默认构造函数,如下所示:

class Test
{
public:
Test() = default;
Test(int t)
{
_b = t;
}
void Display()
{
cout << _a << ' '<< _b << endl;
}
private:
int _a = 0;
int _b;
};

希望这对您有所帮助!

关于c++ - 不同构造函数中的构造函数调用产生错误数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com