【问题标题】:Why can't operator!= do the conversion?为什么不能 operator!= 进行转换?
【发布时间】:2012-11-01 18:07:32
【问题描述】:

我有以下错误代码:

(Visual Studio 错误:)错误 5 错误 C2678: 二进制 '!=' : 未找到采用 '`Node' 类型的左侧操作数的运算符(或没有可接受的转换)

  template <class C, class T>
    C find2 ( C first , C last, T c )
    {
        //
        while ( first != last && *first != c )
        {
            ++first;
        }

        return first;
    }

    struct Node
    {
        Node(int a ,Node* b):val(a),next(b){};
        int val;
        Node* next;
    };

    template <class T>
    struct node_wrap
    {
        T* ptr;

        node_wrap ( T* p = 0 ) : ptr ( p ) {}
        Node& operator*() const {return *ptr;}
        Node* operator->() const {return ptr;}
        node_wrap& operator++ () {ptr = ptr->next; return * this;}
        node_wrap operator++ ( int ) {node_wrap tmp = *this; ++*this; return tmp;}

        bool operator== ( const node_wrap& i ) const {return ptr == i.ptr;}
        bool operator!= ( const node_wrap& i ) const {return ptr != i.ptr;}

    };
    bool operator== ( const Node& node, int n )
    {
        return node.val == n;
    }


    int main()
    {

        Node* node1=new Node(3,NULL);
        Node* node2=new Node(4,NULL);
        node1->next = node2;
        find2 ( node_wrap<Node>(node1), node_wrap<Node>(), 3) ) ;
        delete node1;
        delete node2;
        return 0;
    }

这段代码有什么问题?

【问题讨论】:

  • 您是否要复制 std::liststd::find 已经为您做的事情? :)
  • 不~我只是想尝试一下>这本书

标签: c++


【解决方案1】:

Iterator 的类型为 node_wrap&lt;Node&gt;,因此 *first 在此处返回 Node

    while ( first != last && *first != c )

没有!= 运算符将其与c 的类型(即int)进行比较。您可能的意思是:

    while ( first != last && first->val != c )

相对于定义operator==operator!= 的另一种方法,我建议使用此方法,将Nodeint 进行比较,因为它们是根本不同的类型,不应相互比较。

【讨论】:

  • 迭代器是模板函数中的类型名。
  • 我只是在做一个测试。〜我不会在实际项目中这样做。无论如何谢谢你〜
【解决方案2】:

您正在尝试将Nodeint 进行比较(这是在执行*first != c 时在函数find2 中完成的)。

虽然您提供了 operator== 用于比较 Nodeint,但您还没有提供 operator!= 来做同样的事情。如果你添加一个,这应该可以工作。

【讨论】:

  • interjay 所说的:根据您已有的 operator==() 定义 bool operator!= ( const Node&amp; node, int n )
猜你喜欢
  • 2011-09-14
  • 1970-01-01
  • 2021-01-26
  • 2012-10-17
  • 2016-09-08
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多