【发布时间】:2016-02-05 01:07:08
【问题描述】:
我在这个例子中创建了一个基本上用作公共结构的类,假设类名是X。我想在主函数中声明一个本地对象。我的问题的简短版本是:我知道我们可以做X foo;,但我认为X foo();(附上一对括号)应该可以,我认为第一种用法实际上是第二种用法的简写。完整代码如下:
#include <iostream>
using namespace std;
class X {
public:
int val1;
int val2;
};
int main() {
X a;
X b(); // A warning here
X *c = new X;
X *d = new X();
cout << "val of a: " << a.val1 << " " << a.val2 << endl;
cout << "val of b: " << b.val1 << " " << b.val2 << endl; // Compile error
cout << "val of c: " << c->val1 << " " << c->val2 << endl;
cout << "val of d: " << d->val1 << " " << d->val2 << endl;
return 0;
}
编译器抱怨:
11_stack.cpp:16:6: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
X ab();
^~
11_stack.cpp:16:6: note: replace parentheses with an initializer to declare a variable
X ab();
^~
{}
11_stack.cpp:22:26: error: use of undeclared identifier 'b'
cout << "val of b: " << b.val1 << " " << b.val2 << endl;
^
11_stack.cpp:22:43: error: use of undeclared identifier 'b'
cout << "val of b: " << b.val1 << " " << b.val2 << endl;
^
1 warning and 2 errors generated.
我最初的猜测如下:
- 无论如何,我们都不应该在声明的变量后放置一个空括号。
- 它触发
operator()。
但后来我反驳了这两个假设。我们可以在代码中看到第一个反证:X *c = new X; 和 X *d = new X(); 都有效。对于第二个,我添加了如下代码:
a();
然后我收到编译错误消息:
11_stack.cpp:26:2: error: type 'X' does not provide a call operator
a();
^
那么究竟是什么导致了这个错误呢?
工作环境:
- Mac OS 10.11.3
- 带有标志 c++11 的 g++
- Xcode 版本 7.2 (7C68)
附:如果它太模棱两可,还请帮助我想一个更好的描述性帖子标题......
【问题讨论】:
-
实际上阅读警告会有所帮助。
-
见Most Vexing Parse;这就是 C++11 引入 uniform initialization syntax 的原因。
标签: c++ most-vexing-parse