[SOLVED] operator ==
-
Hi,
@bool operator == (const theList & tmp){
if (this == &tmp){
std::cout << "true";
return true;
}
else
{
std::cout << "false";
return false;
}
}@I have this code, with operator ==.
I debugged but, when the this is equal to &tmp, the loop goes to else. Why? -
are you overriding the == operator in theList class ?
-
[quote author="Neutron Stein" date="1343138503"]are you overriding the == operator in theList class ?[/quote]
Yes. This code is part of the class theList{ ... }
This is one screenshoot.
!http://kepfeltoltes.hu/120724/qt3_www.kepfeltoltes.hu_.png(qt)!On the image looks that this and tmp are same. But the statement will false, always.
-
[quote author="I-sty" date="1343134196"]
@bool operator == (const theList & tmp){
if (this == &tmp){
@
[/quote]You are comparing the pointers. Do you like to compare the content?
Then you need to compare the members individually.
E.g.@class A
{
int a;
int b;
public:
bool operator== ( const A & rhs)
{
return a == rhs.a && b ==rhs.b;
}
};
@
or similar. Otherwise you would need already the operator you are trying to define.NOTE: not tested just typed.
-
When compare the this pointer you making a comparison between memory allocations not objects.
@theList *p_1 = new theList();
theList *p_2;p_2 = p_1;
if (p_1 == p_2)
cout << "Are same allocation";@BR,
-
[quote author="koahnig" date="1343139525"][quote author="I-sty" date="1343134196"]
@bool operator == (const theList & tmp){
if (this == &tmp){
@
[/quote]You are comparing the pointers. Do you like to compare the content?
Then you need to compare the members individually.
E.g.@class A
{
int a;
int b;
public:
bool operator== ( const A & rhs)
{
return a == rhs.a && b ==rhs.b;
}
};
@
or similar. Otherwise you would need already the operator you are trying to define.NOTE: not tested just typed.
[/quote]
Thanks very much koahnig.
You solved my problem. It's working now.