Reputation: 758
I'm new to c++ (coming from Java and C#), and I'm trying to override the == operator in one of my classes so I can see if I have 2 object that have the same value for a given property. I've been doing a bunch of googling and trying to make something that works. What I need is for the == operator to return TRUE when 2 objects have the same _name
text.
Here's the header file:
//CCity.h -- city class interface
#ifndef CCity_H
#define CCity_H
#include <string>
class CCity
{
friend bool operator ==(CCity& a, CCity& b)
{
bool rVal = false;
if (!(a._name.compare(b._name)))
rVal = true;
return rVal;
}
private:
std::string _name;
double _x; //need high precision for coordinates.
double _y;
public:
CCity (std::string, double, double); //Constructor
~CCity (); //Destructor
std::string GetName();
double GetLongitude();
double GetLatitude();
std::string ToString();
};
#endif
In my main() method:
CCity *cit1 = new CCity("bob", 1, 1);
CCity *cit2 = new CCity("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (&cit1 == &cit2)
cout<< "They are the same \n";
else
cout << "They are different \n";
delete cit1;
delete cit2;
The problem is that my code in the friend bool operator ==
block never gets executed. I feel like I'm doing something wrong with either how I'm declaring that operator, or how I'm using it.
Upvotes: 2
Views: 19578
Reputation: 53047
&
takes the address of (you're comparing pointers), when really you want to dereference using *
:
if (*cit1 == *cit2)
cout<< "They are the same \n";
Anyway, there is absolutely no point to using pointers here, let alone dumb ones.
Here's how it would look without them (the proper way):
CCity cit1("bob", 1, 1);
CCity cit2("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (cit1 == cit2)
cout<< "They are the same \n";
else
cout << "They are different \n";
Also, as WhozCraig mentions, consider using const-ref parameters for your operator==
function since it shouldn't modify the arguments.
Upvotes: 5
Reputation: 64308
With this code:
CCity *cit1 = new CCity("bob", 1, 1);
CCity *cit2 = new CCity("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (&cit1 == &cit2)
cout<< "They are the same \n";
else
cout << "They are different \n";
You are comparing the pointers to the pointers to the CCity instances.
You want something like this:
CCity *cit1 = new CCity("bob", 1, 1);
CCity *cit2 = new CCity("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (*cit1 == *cit2)
cout<< "They are the same \n";
else
cout << "They are different \n";
Upvotes: 3