CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2003
    Posts
    4

    operator overloading

    i am trying to overload this function, but the compiler disagrees.

    heres the function.

    bool employee:perator == (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.

  2. #2
    Join Date
    Apr 2003
    Posts
    4
    **** smiles!

  3. #3
    Join Date
    Sep 2002
    Posts
    1,747
    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.
    */*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/

    "It's hard to believe in something you don't understand." -- the sidhi X-files episode

    galathaea: prankster, fablist, magician, liar

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: operator overloading

    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:
    Code:
    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.
    Code:
    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.
    Code:
    employee a;
    employee b;
    if ( b == a ) // the return statement will be used here.
    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured