一个最令人头疼的解析错误:没有参数的构造函数

2021-12-30 00:00:00 constructor standards c++

我在 Cygwin 中使用 g++ 编译了一个 C++ 程序,我有一个类的构造函数没有参数.我有台词:

I was compiling a C++ program in Cygwin using g++ and I had a class whose constructor had no arguments. I had the lines:

MyClass myObj();
myObj.function1();

当我尝试编译它时,我收到了消息:

And when trying to compile it, I got the message:

错误:请求'myObj'中的成员'function1',它是非类类型'MyClass()()'

error: request for member 'function1' in 'myObj', which is of non-class type 'MyClass ()()'

经过一番研究,我发现修复方法是将第一行更改为

After a little research, I found that the fix was to change that first line to

MyClass myObj;

我可以发誓我以前在 C++ 中做过带括号的空构造函数声明.这可能是我使用的编译器的限制,还是语言标准真的说不要在没有参数的构造函数中使用括号?

I could swear I've done empty constructor declarations with parentheses in C++ before. Is this probably a limitation of the compiler I'm using or does the language standard really say don't use parentheses for a constructor without arguments?

推荐答案

虽然 MyClass myObj(); 可以被解析为带有空初始化器或函数声明的对象定义,但语言标准规定歧义总是以有利于函数声明的方式解决.在其他上下文中允许使用空括号初始值设定项,例如在 new 表达式中或构造一个 值初始化 临时.

Although MyClass myObj(); could be parsed as an object definition with an empty initializer or a function declaration the language standard specifies that the ambiguity is always resolved in favour of the function declaration. An empty parentheses initializer is allowed in other contexts e.g. in a new expression or constructing a value-initialized temporary.

相关文章