C++11 Difference in Constructors (Braces)

感情迁移 提交于 2020-01-21 11:42:09

问题


I am quite new to C++ and have observed, that the following lines of code act differently

MyClass c1;
c1.do_work() //works
MyClass c2();
c2.do_work() //compiler error c2228: left side is not a class, structure, or union.
MyClass c3{};
c3.do_work() //works

with a header file as

class MyClass {
public:
    MyClass();
    void do_work();
};

Can you explain me, what the difference between the three ways of creating the object is? And why does the second way produce a compiler error?


回答1:


Ways one and three call the default constructor.

MyClass c3{};

Is a new initialization syntax called uniform initialization. This is called default brace initialization. However:

MyClass c2();

Declares a function c2 which takes no parameters with the return type of MyClass.




回答2:


The second version

MyClass c2();

is a function declaration - see the most vexing parse and gotw.

The first case is default initialisation.

The last case, new to C++11, will call the default constructor, if there is one, since even though it looks like an initialiser list {}, it's empty.



来源:https://stackoverflow.com/questions/24307913/c11-difference-in-constructors-braces

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