【问题标题】:Why parenthesis after an object variable declaration cause error (C++)? [duplicate]为什么对象变量声明后的括号会导致错误(C++)? [复制]
【发布时间】: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.

我最初的猜测如下:

  1. 无论如何,我们都不应该在声明的变量后放置一个空括号。
  2. 它触发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)

附:如果它太模棱两可,还请帮助我想一个更好的描述性帖子标题......

【问题讨论】:

标签: c++ most-vexing-parse


【解决方案1】:

cd 是指针,所以你需要c-&gt;val1 而不是使用.

【讨论】:

  • 这甚至不是 OP 的问题,虽然它一旦 OP 解决了其他问题
  • 谢谢,我的意思是 -> 我已经相应地更正了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 2010-09-19
  • 2022-06-10
  • 1970-01-01
相关资源
最近更新 更多