我有一个基类
class Animal
使用纯虚函数和一组派生类
class Monkey : public Animal class Snake : public Animal
我想实现一个比较操作,以便在我的代码中遇到两个指向动物的指针
Animal* animal1 Animal* animal2
我可以将它们相互比较.如果animal1和animal2具有不同的派生类别,则比较应该产生错误.如果它们具有相同的派生类,则应返回比较运算符的输出.
有人能指出我实现这个的好方法吗?
解决方法
哇,很多其他答案都是如此完全没必要. dynamic_cast-它存在,使用它.
class Animal {
public:
virtual bool operator==(const Animal& other) = 0;
virtual ~Animal() = 0;
};
template<class T> class AnimalComp : public Animal {
public:
virtual bool operator==(const Animal& ref) const {
if (const T* self = dynamic_cast<const T*>(&ref)) {
return ((T*)this)->operator==(*self);
}
return false;
}
virtual bool operator!=(const Animal& ref) const {
if (const T* self = dynamic_cast<const T*>(&ref)) {
return ((T*)this)->operator!=(*self);
}
return true;
}
};
class Monkey : public AnimalComp<Monkey> {
public:
virtual bool operator==(const Monkey& other) const {
return false;
}
virtual bool operator!=(const Monkey& other) const {
return false;
}
};
class Snake : public AnimalComp<Snake> {
public:
virtual bool operator==(const Snake& other) const {
return false;
}
virtual bool operator!=(const Snake& other) const {
return false;
}
};
编辑:在我的自动模板实现之前鞠躬!
编辑编辑:我做的一件事就是忘记将它们标记为const,这对我来说是错误的.我不会为不做而道歉!=因为,让我们面对现实,实施它是一件轻而易举的事.
更多编辑:耶稣基督家伙,这不是如何写的例子!=或==,这是如何使用CRTP的一个例子.如果你不喜欢我选择实施我的!=或==,你可以起诉.