C++ check if two objects are equal with overloading == operator, always false?

后端 未结 2 1365
清歌不尽
清歌不尽 2021-01-26 03:03

I\'m attempting to check if two objects are equal by overloading the \'==\' operator for the class. Based on everything I\'ve read here on Stack Overflow and elsewhere, for exa

相关标签:
2条回答
  • 2021-01-26 03:46

    Your operator== returns true only when comparing an object to itself. Two different objects will never be equal, because different objects have different addresses.

    It seems that you really do want this behavior (though you don't specify it). However, your program copies objects around too much:

    findVectorOfMatchingChars(PossibleChar possibleChar, ...);
    

    The above declaration makes the function receive the "possible char" by value, copying it into a new object. This will never be equal to any other existing objects!

    You probably want:

    findVectorOfMatchingChars(const PossibleChar& possibleChar, ...);
    

    This will pass the "possible char" by reference, and its address will be the address of an existing "possible char" (which, I guess, is one of the possible chars in your vector).

    You might even pass an address:

    findVectorOfMatchingChars(const PossibleChar* possibleChar, ...);
    

    This will warn the unsuspecting user of your code that it does something with addresses. This will also prevent a naive user from passing a newly constructed object:

    findVectorOfMatchingChars(PossibleChar(), ...); // error
    
    PossibleChar x;
    findVectorOfMatchingChars(&x, ...); // works
    
    0 讨论(0)
  • 2021-01-26 03:54

    Your current operator== assumes the objects to be at the same address, so if you did something like

    PossibleChar p1;
    PossibleChar p2 = p1;
    std::cout << p1 == p2 << '\n';
    

    it would print false.

    If that is indeed what you want, alright.
    If it is not, you will need to define an operator==, which compares all necessary1 members of the objects, not the addresses.


    1 "necessary" means "members defining the state of the object" here, that is, it depends on the class which members should be compared.

    0 讨论(0)
提交回复
热议问题