情况1:类中显式定义了默认构造函数
此时new Test()和new Test并无区别,都会调用定义的构造函数,所以下面程序中的输出结果一样。
class Test {
private:
int N;
public:
Test() { N = 1; }
int GetNum() { return N; }
};
int main()
{
Test* AA = new Test();
Test* BB = new Test;
cout << AA->GetNum() << '\t';
cout << BB->GetNum() << endl;
return 0;
}输出结果:
1 1
请按任意键继续. . .情况2:没有定义默认构造函数也没有虚函数(此时编译器会生成一个默认构造函数,称为合成构造函数)
此时new Test() 会调用合成构造函数,该构造函数会将类成员初始化,所以下面程序运行后会输出0;new Test 不会调用合成构造函数,类成员N为随机值。
class Test {
private:
int N;
public:
// Test() { N = 1; }
int GetNum() { return N; }
};
int main()
{
Test* AA = new Test();
Test* BB = new Test;
cout << AA->GetNum() << '\t';
cout << BB->GetNum() << endl;
return 0;
}输出结果:
0 -842150451
请按任意键继续. . .情况3:对于内置型的变量,规则一致:
int* pnA = new int;
int* pnB = new int();
cout << *pnA << '\t' << *pnB << endl;输出结果:
-842150451 0
请按任意键继续. . .结论:所以平时还是得带上()啊!
情况4:如果创建一个对象,类中没有显示定义构造函数:
class Test {
private:
int N;
public:
// Test() { N = 1; }
int GetNum() { return N; }
};
int main()
{
Test* AA = new Test();
Test* BB = new Test;
Test CC;
cout << AA->GetNum() << '\t';
cout << BB->GetNum() << '\t';
cout << CC.GetNum() << endl;
return 0;
}输出结果:
0 -842150451 -858993460
请按任意键继续. . .注意:如果类中显示定义了非默认构造函数且未显示定义默认构造函数,则不能用new Test 和new Test() ,会提示错误!
本文探讨了C++中new操作符后跟类名与类名加括号在不同情况下的行为差异,包括类中是否定义了默认构造函数、成员变量初始化及对象创建等场景。
3081

被折叠的 条评论
为什么被折叠?



