带空括号的默认构造函数 [英] Default constructor with empty brackets

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

问题描述

有没有什么好的理由,一组空的圆括号(括号)对于调用C ++中的默认构造函数是无效的?

Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?

MyObject  object;  // ok - default ctor
MyObject  object(blah); // ok

MyObject  object();  // error



我似乎每次都自动键入()。

I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?

推荐答案

最讨厌的解析

这被称为C ++的最烦琐的解析。基本上,编译器可以解释为声明的任何内容都将被解释为声明。

This is known as "C++'s most vexing parse". Basically, anything that can be interpreted by compiler as a declaration will be interpreted as a declaration.

同样问题的另一个实例:

Another instance of the same problem:

std::ifstream ifs("file.txt");
std::vector<T> v(std::istream_iterator<T>(ifs), std::istream_iterator<T>());

v 被解释为函数声明有2个参数。

v is interpreted as a declaration of function with 2 parameters.

解决方法是添加另一对括号:

The workaround is to add another pair of parentheses:

std::vector<T> v((std::istream_iterator<T>(ifs)), std::istream_iterator<T>());

或者,如果你有C ++ 11和列表初始化:

Or, if you have C++11 and list-initialization (also known as uniform initialization) available:

std::vector<T> v{std::istream_iterator<T>{ifs}, std::istream_iterator<T>{}};

这样,就没有办法解释为函数声明。

With this, there is no way it could be interpreted as a function declaration.

这篇关于带空括号的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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