问题描述
#include <iostream>
using namespace std;
class CTest
{
int x;
public:
CTest()
{
x = 3;
cout << "A";
}
};
int main () {
CTest t1;
CTest t2();
return 0;
}
CTest t1当然打印A。
CTest t1 prints "A" of course.
但是它似乎在t2()什么都没有发生,但代码运行良好。
But it seems like nothing happens at t2(), but the code runs well.
那么我们使用没有参数的括号吗?或者为什么我们可以这样使用它?
So do we use those parentheses without argument? Or why can we use it this way?
推荐答案
这是C ++语法的一个奇怪。
This is a quirk of the C++ syntax. The line
CTest t1;
声明一个类型为 CTest
的局部变量 t1
。它隐式调用默认构造函数。另一方面,行
declares a local variable of type CTest
named t1
. It implicitly calls the default constructor. On the other hand, the line
CTest t2();
是不一个变量声明, t2
不带参数并返回 CTest
。 t2
的构造函数没有被调用的原因是因为这里没有创建对象。
Is not a variable declaration, but a local prototype of a function called t2
that takes no arguments and returns a CTest
. The reason that the constructor isn't called for t2
is because there's no object being created here.
在C ++ 11中,你也可以选择
In C++11, you can alternatively say
CTest t2{};
这实际上是调用默认构造函数。
Which does actually call the default constructor.
希望这有助于!
这篇关于实例化带或不带括号的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!