我想在以下类上实现“less”类型的操作:
class Base {
public:
virtual int type() const = 0;
private:
int b;
};
class Derived1 : public Base{
public:
virtual int type() const { return 1; }
private:
int d1;
};
class Derived2 : public Base{
public:
virtual int type() const { return 2; }
private:
int d2;
};
哪里o1 < o2
如果其类型较小且类型相等,则比较元素(首先是 b,然后是 d1 或 d2)。
请注意,还有其他具有类似问题结构的操作(例如等于)。
如何在不使用 dynamic_cast
的情况下执行此操作? ?
最佳答案
您不需要dynamic_cast
或type
。就此而言,也根本没有公共(public)成员。
class Base {
virtual bool less( Base const & rhs ) const {
return false;
}
int b;
friend bool operator < ( Base const & lhs, Base const & rhs ) {
std::type_info const & ltype = typeid (lhs);
std::type_info const & rtype = typeid (rhs);
if ( ltype == rtype ) {
if ( lhs.b < rhs.b ) return true;
if ( rhs.b < lhs.b ) return false;
return lhs.less( rhs ); // Dynamic types of lhs and rhs already match.
}
return ltype.before( rtype );
}
};
class Derived1 : public Base{
virtual bool less( Base const & rhs_base ) const {
// Since rhs_base is known to be of this type, use static_cast.
Derived1 const & rhs = static_cast< Derived1 const & >( rhs_base );
return d1 < rhs.d1;
}
int d1;
};
// Same for Derived2
关于c++ - 如何在没有 dynamic_cast 的派生类型上实现 "less"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024012/