简体   繁体   English

C ++ 11构造函数(大括号)的区别

[英]C++11 Difference in Constructors (Braces)

I am quite new to C++ and have observed, that the following lines of code act differently 我对C ++很陌生并观察到,以下代码行的行为不同

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? 为什么第二种方式会产生编译错误?

The second version 第二个版本

MyClass c2();

is a function declaration - see the most vexing parse and gotw . 是一个函数声明 - 看到最令人烦恼的解析getw

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. 最后一种情况,C ++ 11的新手,将调用默认构造函数(如果有的话),因为即使它看起来像初始化列表{} ,它也是空的。

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 . 声明一个函数c2 ,它不带任何带MyClass返回类型的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM