C++ 不同构造函数中的构造函数调用产生错误数据
以下是复制我的问题的最小程序:C++ 不同构造函数中的构造函数调用产生错误数据,c++,constructor,C++,Constructor,以下是复制我的问题的最小程序: #include <iostream> using namespace std; class Test { public: Test() { _a = 0; } Test(int t) { Test(); _b = t; } void Display() { cout << _a << ' ' &l
#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;
}
#包括
使用名称空间std;
课堂测试
{
公众:
测试()
{
_a=0;
}
测试(int t)
{
Test();
_b=t;
}
无效显示()
{
cout这里的问题在代码中:
Test(int t)
{
Test();
_b = t;
}
这不会调用默认的Test
构造函数,然后设置\u b=t
。相反,它使用默认构造函数创建类型为Test
的临时对象,忽略该临时对象,然后设置\u b=t
。因此,默认构造函数不会为接收方对象运行,因此<代码>\u 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;
};
类测试
{
公众:
Test()=默认值;
测试(int t)
{
_b=t;
}
无效显示()
{
默认初始值设定项语法为cout+1,比其他选项简洁得多。注意:请记住,可以使用单个参数调用的构造函数最好声明为显式
,以避免意外转换。