我收到一个编译错误,说“左”和“右”不明确。
我是否在错误的地方宣布左,右?
我该如何解决?
最小测试用例:
#include <iostream>
using namespace std;
int left = 0, right = 0;
int main()
{
cout << left;
cout << right;
}
给:
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&)
最佳答案
观察错误消息:
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&)
令人生畏的是,但基本上这就是它的意思:
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’
因此,
left
和right
已经在namespace std
中定义了,您将使用using namespace std
导入所有这些内容。这就是为什么你有歧义。要解决此问题,最简单的更改是删除using namespace std;
并添加using std::cin; using std::cout;
,但这对我来说似乎是太多的全局变量。顺便说一句,您应该将代码合并到问题中。这里的问题可能比粘贴的问题要长,如果没人能看到整个问题,我的回答将毫无意义。
关于c++ - 编译错误:左歧义,右歧义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15516654/