Instantiate class with or without parentheses? [duplicate]

浪子不回头ぞ 提交于 2019-12-17 18:27:27

问题


#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 prints "A" of course.

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?


回答1:


This is a quirk of the C++ syntax. The line

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();

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.

In C++11, you can alternatively say

CTest t2{};

Which does actually call the default constructor.

Hope this helps!



来源:https://stackoverflow.com/questions/9490349/instantiate-class-with-or-without-parentheses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!