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

后端 未结 2 1364
清歌不尽
清歌不尽 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
    

提交回复
热议问题