C ++ 11构造函数的差异(大括号) [英] C++11 Difference in Constructors (Braces)

查看:230
本文介绍了C ++ 11构造函数的差异(大括号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++非常陌生,并且观察到以下代码行的行为不同。

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?

推荐答案

方法一和三调用默认构造函数。

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

声明一个不带参数的函数 c2 返回类型为 MyClass

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

这篇关于C ++ 11构造函数的差异(大括号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆