Click to See Complete Forum and Search --> : operator overloading
Hexalon
April 24th, 2003, 04:41 PM
i am trying to overload this function, but the compiler disagrees.
heres the function.
bool employee::operator == (const employee &p)
{
return *this == p;
}
heres my use of the class and and the overloaded function.
int main(void)
{
employee emp1;
employee emp2;
if(emp1 == emp2)
std::cout << "\n\t\nobjects equal\n\n";
return 0;
}
heres the error the compiler gives.
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const employee' (or there is no acceptable conversion)
any suggestions.
Hexalon
April 24th, 2003, 04:41 PM
**** smiles!
galathaea
April 24th, 2003, 04:49 PM
You have a circular definition. You define logical equality testing in terms of the same logical equality testing. Instead, do a memberwise test of those things in your class you use to define equality.
Paul McKenzie
April 24th, 2003, 05:22 PM
Originally posted by Hexalon
i am trying to overload this function, but the compiler disagrees.
heres the function.
bool employee::operator == (const employee &p)
{
return *this == p;
}
As galathaea pointed out, you have defined an operator ==, but then you tell it to use the operator == that you are trying to define. Something like this is what you're looking for:
bool employee::operator == (const employee &p)
{
if ( this == &p ) return true;
return (employee.name == p.name &&
employee.address == p.address);
// Or whatever fields you use to compare for equal employees
}
The first == compares pointers. This is a check to see if the instances are the same, not a check to see whether two distinct objects are equal. This is done because there is no need to check if the same instances are equal -- they're always equal.
employee a;
if ( a == a ) // this is covered by the first if() statement
The check for two distinct employee objects being equal is done in the return statement.
employee a;
employee b;
if ( b == a ) // the return statement will be used here.
Regards,
Paul McKenzie
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.