Comparison operator overloading

前端 未结 5 1324
忘了有多久
忘了有多久 2020-12-30 18:59

Which is best practice (in this case):

bool Foo::operator==(const Foo& other) {
  return bar == other.bar;
}

// Implementation 1
bool Foo::operator!=(co         


        
相关标签:
5条回答
  • 2020-12-30 19:33

    You should always use what you have when overloading comparison operators. The only two you should need to define are operator== and operator<. The rest you can write in terms of these two. It's less error-prone, as if you have a mistake, it's only in one place.

    One of the main features of OOP is code reusability. If you've already written the code, why write it again? Stick to what you have, and you'll only have one thing to test.

    It's rather like declaring a constant, and then using it in several spots throughout your file.

    0 讨论(0)
  • 2020-12-30 19:34

    In general, implementation 2 is better for many reasons. First of all, you don't write (almost) duplicate code. If you need to change it (because the class has grown or there has been a bug), again with implementation 2 you change only 1 place. That is, implementation 2 makes your code more consistent and less error prone.

    0 讨论(0)
  • 2020-12-30 19:35

    Implementation 2 is better because it makes use of the already defined operator==. Also those operator functions should be const because they don't modify the object.

    0 讨论(0)
  • 2020-12-30 19:35

    None of the above.

    I wish I could find the paper that really goes over this in detail but I can't recall the name.

    Your comparison operations should be external. Your interface should be sufficient to finding the state of an object and the state of the object should be dictating comparison. It should be possible to write "equals" outside of your class, and thus any comparison really, and that being possible...you want to.

    0 讨论(0)
  • 2020-12-30 19:46

    The second implementation has the notable constraint that == will always be the boolean opposite of !=. This is probably what you want, and it makes your code easier to maintain because you only have to change one implementation to keep the two in sync.

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