微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/c/115569.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐