编译错误:左歧义,右歧义

use*_*433 2 c++ data-structures

我收到一个编译错误,说“左”和“右”不明确。

我是否在错误的地方宣布左,右?

  • 在main内部声明也无济于事
  • 将函数定义移至main上方无济于事

我该如何解决?

最小测试用例:

#include <iostream>
using namespace std;
int left = 0, right = 0;
int main()
{
    cout << left;
    cout << right;
}
Run Code Online (Sandbox Code Playgroud)

正在给:

prog.cpp: In function ‘int main()’:
prog.cpp:6:13: error: reference to ‘left’ is ambiguous
prog.cpp:3:5: error: candidates are: int left
In file included from /usr/include/c++/4.7/ios:43:0,
                 from /usr/include/c++/4.7/ostream:40,
                 from /usr/include/c++/4.7/iostream:40,
                 from prog.cpp:1:
/usr/include/c++/4.7/bits/ios_base.h:918:3: error:
             std::ios_base& std::left(std::ios_base&)
prog.cpp:7:13: error: reference to ‘right’ is ambiguous
prog.cpp:3:15: error: candidates are: int right
In file included from /usr/include/c++/4.7/ios:43:0,
                 from /usr/include/c++/4.7/ostream:40,
                 from /usr/include/c++/4.7/iostream:40,
                 from prog.cpp:1:
/usr/include/c++/4.7/bits/ios_base.h:926:3: error:
             std::ios_base& std::right(std::ios_base&)
Run Code Online (Sandbox Code Playgroud)

Dan*_*ons 5

观察错误消息:

raw.cpp:105: error: reference to ‘right’ is ambiguous
raw.cpp:5: error: candidates are: int right
/usr/include/c++/4.2.1/bits/ios_base.h:917: error:
   std::ios_base& std::right(std::ios_base&)
Run Code Online (Sandbox Code Playgroud)

令人生畏的是,但基本上这就是它的意思:

raw.cpp:105: error: There's more than one ‘right’ here
One of them is yours: raw.cpp:5  int right
Another one isn't: <bits/ios_base.h:917>: some crap in namespace ‘std’
Run Code Online (Sandbox Code Playgroud)

因此leftright并且已经在中定义了namespace std,您将在其中导入所有内容using namespace std。这就是为什么你有歧义。要解决此问题,最简单的更改是删除using namespace std;和添加,using std::cin; using std::cout;但是对于我来说,这看起来像是太多的全局变量。

顺便说一句,您应该将代码合并到问题中。这里的问题可能比粘贴的问题要长,如果没人能看到整个问题,我的回答将毫无意义。