Reputation: 993
I'm very new to C++ and trying to get up this simple example working, but for some reason I get unexpected results.
#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";
}
I'm trying to create custom operator for ==
bool operator==(const node &rhs) const { return data == rhs.data; }
The second line prints what I expected to happen, it looks like the operator overloaded function is simply not run?
Upvotes: 0
Views: 2924
Reputation: 286
When you do one == three
you are actually comparing pointers rather than the objects themselves. Try: *one == *three
.
Upvotes: 2
Reputation: 1342
You need to dereference the node structure, instead of comparing pointers:
if (*one == *two) {}
But as others pointed out, you should consider not using pointers, so just do:
node one;
node two;
....
if (one == two) {}
Upvotes: 5