带或不带括号的实例化类?

2021-12-30 00:00:00 constructor c++
#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 C++ syntax. The line

CTest t1;

声明一个名为 t1CTest 类型的局部变量.它隐式调用默认构造函数.另一方面,线

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.

如果要声明对象类型的局部变量并使用默认构造函数,则应省略括号.

If you want to declare a local variable of object type and use the default constructor, you should omit the parentheses.

在 C++11 中,你也可以说

In C++11, you can alternatively say

CTest t2{};

实际上调用了默认构造函数.

Which does actually call the default constructor.

希望这有帮助!

相关文章