2013-03-20 48 views
2

我收到编译错误,说'左'和'右'不明确。编译错误:左边模糊不清,右边模糊

我是否宣布左,右对错?

  • 内主声明并没有帮助
  • 移动上述主要功能的定义并不能帮助

如何我会解决这个问题?

最少测试用例:

#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&) 
+3

对未来的建议 - 构建[最小测试用例](https://ideone.com/c2DqtQ)并将代码粘贴到问题中,而不仅仅是指向它的链接。 – Dukeling 2013-03-20 06:30:06

+0

我只是无法理解此网站上的代码格式! – user1776433 2013-03-20 06:36:54

+0

现在你知道你为什么不使用'namespace std;'! – 2013-03-20 06:36:58

回答

3

观察错误消息:

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’ 

因此leftright已在namespace std中定义,您正在导入所有using namespace std。这就是你含糊不清的原因。解决这个问题的最简单的方法是删除using namespace std;并添加using std::cin; using std::cout;,但这看起来像是我的口味中的太多全局变量。

顺便说一句,你应该把你的代码并入你的问题。这个问题在这里可能会比粘贴时间更长,如果没有人能看到整个问题,我的回答就没有意义了。

+0

我不知道左和右是在命名空间std中定义的,我将它们更改为lft和rght。非常感谢。 – user1776433 2013-03-20 06:34:52

+1

如果你在我的班级,我会给你写一个字母等级,只是为了这些新的变量名。 'left_index'或'deque_left'怎么样? – 2013-03-20 06:38:02

+0

或者不要使用'using namespace std;',而是使用'std ::'前缀你想要的项目,或者指定你从'std'导入的内容。 (我认为':: left'和':: right'也会起作用;不过我不确定我会推荐这个符号。) – 2013-03-20 06:41:06