c – 实现基类比较的正确方法是什么?

c – 实现基类比较的正确方法是什么?,第1张

概述我有一个基类 class Animal 使用纯虚函数和一组派生类 class Monkey : public Animal class Snake : public Animal 我想实现一个比较 *** 作,以便在我的代码中遇到两个指向动物的指针 Animal* animal1Animal* animal2 我可以将它们相互比较.如果animal1和animal2具有不同的派生类别,则比较应该产生错 我有一个基类
class Animal

使用纯虚函数和一组派生类

class Monkey : public Animal class Snake : public Animal

我想实现一个比较 *** 作,以便在我的代码中遇到两个指向动物的指针

Animal* animal1Animal* 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的一个例子.如果你不喜欢我选择实施我的!=或==,你可以起诉.

总结

以上是内存溢出为你收集整理的c – 实现基类比较的正确方法是什么?全部内容,希望文章能够帮你解决c – 实现基类比较的正确方法是什么?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1233393.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存