C ++运算符重载是否相等

时间:2014-09-30 20:20:06

标签: c++ operator-overloading

我对C ++很陌生,试图让这个简单的例子起作用,但由于某种原因,我得到了意想不到的结果。

代码:

#include<iostream>

using namespace std;

struct node{
    string data;
    node *next;
    node *prev;

    node() {}

    bool operator==(const node &rhs) const {
        return data == rhs.data;
    }
};

int main(){
    bool loop=true;
    node* one = new node();
    one->data = "oddly specific";

    node* two = new node();
    two->data = "Something else";

    node* three = new node();
    three->data = "oddly specific";

    if (one == two)
        cout << "one == two";
    else
        cout << "one != two";
    if (one == three)
        cout << "one == three";
    else
        cout << "one != three";

    cout << endl;

    if(one->data == two->data)
        cout << "one == two";
    else
        cout << "one != two";
    if(one->data == three->data)
        cout << "one == three";
    else
        cout << "one != three";
}

我正在尝试为==

创建自定义运算符
bool operator==(const node &rhs) const { return data == rhs.data; }

第二行打印出我预期发生的情况,看起来操作符重载函数根本就没有运行?

2 个答案:

答案 0 :(得分:5)

您需要取消引用节点结构,而不是比较指针:

if (*one == *two) {}

但正如其他人所指出的那样,你应该考虑不使用指针,所以只需这样做:

node one;
node two;
....
if (one == two) {}

答案 1 :(得分:2)

执行one == three时,实际上是在比较指针而不是对象本身。尝试:*one == *three