Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overloading operator== 1

Status
Not open for further replies.

chpicker

Programmer
Apr 10, 2001
1,316
I created a simple class that contains 3 numeric values, and I want to overload the == operator so I can compare 2 instances of the class. The function will simply test all 3 numeric values and return true only if all 3 are identical. The problem is that the compiler only allows me to pass ONE argument to operator==, so how can I figure out what to compare it to? Here's my code:
Code:
class Loc
{
public:
	int x,y,z;
	bool operator==(Loc,Loc);
};

bool Loc::operator==(Loc a,Loc b)
{
	if((a.x==b.x) && (a.y==b.y) && (a.z==b.z))
		return true;
	else
		return false;
}
When I compile, I get "error C2804: binary 'operator ==' has too many parameters". If I remove the second parameter, it compiles...but what can I put into the function body to actually do the comparison? What do I compare "Loc a" to?
 
Yes, it looks like an extern operator ==. Change it to:

class Loc
{
public:
int x,y,z;
bool operator==(Loc);
};
bool Loc::eek:perator==(Loc b)
{
if((x==b.x) && (y==b.y) && (z==b.z))
return true;
else
return false;
}

or to:


class Loc
{
public:
int x,y,z;
};
operator==(Loc a,Loc b)
{
if((a.x==b.x) && (a.y==b.y) && (a.z==b.z))
return true;
else
return false;
}

John Fill
1c.bmp


ivfmd@mail.md
 
by the way, you can:

return ((x==b.x) && (y==b.y) && (z==b.z));

instead of:

if((x==b.x) && (y==b.y) && (z==b.z))
return true;
else
return false;

John Fill
1c.bmp


ivfmd@mail.md
 
Yes! Thanks, John...once again, these forums have proven to be THE best place to look for help. :eek:)
 
class Loc
{
public:
int x,y,z;
bool operator ==(Loc myLoc){
return ( myLoc.x == x) &&
( myLoc.y == y) &&
( myLoc.z == z);
}
};

thats your class.

to compare 3 things

Loc a,b,c;

if (a==b && b== c)

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top