我会实现它是这样的:
class A{
int a;
public:
virtual int Compare(A *other);
};
class B : A{
int b;
public:
/*override*/ int Compare(A *other);
};
int A::Compare(A *other){
if(!other)
return 1; /* let's just say that non-null > null */
if(a > other->a)
return 1;
if(a < other->a)
return -1;
return 0;
}
int B::Compare(A *other){
int cmp = A::Compare(other);
if(cmp)
return cmp;
B *b_other = dynamic_cast<B*>(other);
if(!b_other)
throw "Must be a B object";
if(b > b_other->b)
return 1;
if(b < b_other->b)
return -1;
return 0;
}
这是非常相似的IComparable
模式在.NET中,它工作得很好。
编辑:
一个警告上述是a.Compare(b)
(其中a
是A和b
是B)可以返回平等,并且将从未抛出异常,而b.Compare(a)
意愿。有时候这就是你想要的,有时候不是。如果不是,那么你可能不希望您的Compare
功能是虚拟的,或者你想在基础Compare
功能比较type_info
S,如:
int A::Compare(A *other){
if(!other)
return 1; /* let's just say that non-null > null */
if(typeid(this) != typeid(other))
throw "Must be the same type";
if(a > other->a)
return 1;
if(a < other->a)
return -1;
return 0;
}
注意,派生类Compare
功能别因为他们应该调用基类的Compare
,其中type_info
将发生比较。但是,您可以使用static_cast
替代覆盖的Compare
函数中的dynamic_cast
。
不,使用==运算符是有意义的。这就是它的目的。不需要比较功能。 – jalf 2008-11-16 17:34:18
@jalf我认为他希望做比strcmp()更大,更小,更小的比较。注意Compare()返回一个int值,而不是一个bool值。 – 2009-05-08 20:48:31