错误C2872:'range_error':模糊符号

时间:2010-10-29 15:37:57

标签: c++ visual-studio-2010 pointers ambiguous

我已经搜索了SO和google,我没有在两个地方声明相同的变量,也没有以奇怪的方式包含某些东西......我知道。插入方法应该工作正常,这是一个预先编写的方法(我想这也可能是错的..大声笑)。这是我得到的错误。

错误:

error C2872: 'range_error' : ambiguous symbol
........ while compiling class template member function 'Error_code List<List_entry>::insert(int,const List_entry &)'

对我来说,insert方法看起来没问题,我没有看到正在与0比较的位置变量或在构造函数中声明为0的count以返回range_error的任何问题。

插入方法:

template <class List_entry>
Error_code List<List_entry>::insert(int position, const List_entry &x){
    Node<List_entry> *new_node, *following, *preceding;
    if(position < 0 || position > count){
        return range_error;
    }
    if(position == 0){
        if(count == 0) following = nullptr;
        else {
            set_position(0);
            following = current;
        }
        preceding = nullptr;
    }
    else {
        set_position(position - 1);
        preceding = current;
        following = preceding->next;
    }

    new_node = new Node<List_entry>(x, preceding, following);

    if(new_node == nullptr) return overflow;
    if(preceding != nullptr) preceding->next = new_node;
    if(following != nullptr) following->back = new_node;

    current = new_node;
    current_position = position;
    count++;

    return success;
}

问题可能在于我没有overloaded =运算符的实现吗?

此处的所有代码:pastie.org/1258159

4 个答案:

答案 0 :(得分:7)

range_error在您的代码(在全局命名空间中)和标准库(在std命名空间中)中定义。使用using namespace std;将整个Standard命名空间拖动到全局命名空间会产生歧义。您应该至少执行以下操作之一:

  • 从全局命名空间中删除using namespace std;要么使用函数中的命名空间,要么只使用您需要的名称,或者在使用它们时限定所有标准名称
  • 仔细选择自己的名字以避免与标准名称冲突
  • 将您自己的名字放在命名空间内(不要将其拉入全局命名空间)。

答案 1 :(得分:2)

range_errorstdexcept标头中定义的类。在您的代码中,您可能使用具有相同名称的常量,并使用std::range_error指令使using namespace std;可见,这会导致歧义。重命名常量或修改使用指令。

例如:

#include <stdexcept>

using namespace std;

int range_error = 42;

int main()
{
    return range_error;
}

上面的代码会导致同样的错误。

答案 2 :(得分:2)

您在顶部的using namespace std;语句会从stdexcept标题中声明std::range_error例外。这与您的enum值冲突。将enum括在struct并完全符合条件:

struct my_errors {
    enum {
        // ...
        range_error
    };
};
// ...
return my_errors::range_error;

或者只是避免使用标准库中的名称。

答案 3 :(得分:2)

替代解决方案(除已经提供的解决方案之外)是对名称::range_error进行限定。这就是命名空间的用途。这就是为什么标准的lib东西在名称空间std中被关闭了,所以这样的冲突可以非常轻松解决。

在上面的代码中,

if(new_node == nullptr) return overflow;

永远不会执行return

你能明白为什么吗?

干杯&amp;第h。,

PS:重新使用粘贴本代码,请注意main必须包含结果类型int,而不是void。此外,许多函数无法返回值。

相关问题