C++核心准则C.87:小心基类的相等运算符
紫黄晶
C.87: Beware of == on base classes
C.87:小心基类的相等运算符
It is really hard to write a foolproof and useful == for a hierarchy.
为继承体系写出简单又好用的相等运算符真的很难。
class B {
string name;
int number;
virtual bool operator==(const B& a) const
{
return name == a.name && number == a.number;
}
// ...
};
B's comparison accepts conversions for its second operand, but not its first.
B的相等比较运算符的第二个操作数接受类型转换,但是第一个不行。
class D :B {
char character;
virtual bool operator==(const D& a) const
{
return name == a.name && number == a.number && character == a.character;
}
// ...
};
B b = ...
D d = ...
b == d; // compares name and number, ignores d's character
d == b; // error: no == defined
D d2;
d == d2; // compares name, number, and character
B& b2 = d2;
b2 == d; // compares name and number, ignores d2's and d's character
Of course there are ways of making == work in a hierarchy, but the naive approaches do not scale
当然有办法让相等比较运算符在继承体系中动作,但是简单的方法不行。
This rule applies to all the usual comparison operators: !=, <, <=, >, and >=.
本规则适用于所有的常见比较运算符:!=, <, <=, >, 和 >=。
Flag a virtual operator==(); same for other comparison operators: !=, <, <=, >, and >=.
提示被定义为虚函数的相等比较运算符;其他比较运算符也一样:!=, <, <=, >, 和 >=。
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c87-beware-of--on-base-classes
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!