过载==和!=C++中具有多态性的运算符

Overloading == and != operators in C++ with polymorphism

本文关键字:多态性 运算符 C++ 过载      更新时间:2023-10-16

事情是这样的。我有一个基础班和4个儿童班。

class Base{
  public:
    virtual int getType() const = 0;
};
class Type1 : public Base{
  public:
    virtual int getType() const {
        return 1;
    };
};
class Type2 : public Base{
  public:
    virtual int getType() const {
        return 2;
    };
};
class Type3 : public Base{
  public:
    virtual int getType() const {
        return 3;
    };
};
class Type4 : public Base{
  public:
    virtual int getType() const {
        return 4;
    };
};

我需要重载对所有子类执行相同操作的==!=运算符,只需检索类型值并进行比较即可。因此,我自然会在Base类中实现运算符,同时引用Base作为两个操作数,但当我这样做时,当我在子视图上使用运算符时,我的IDE开始尖叫,它无法比较结构。

所以问题是,有没有一种方法可以让我只实现一次运算符,而不必为每个子类的组合指定它们?

谢谢!

我对这个运算符没有任何问题:

bool operator==(Base const& x, Base const& y)
{
    return x.getType() == y.getType();
}

除非有可访问性问题:您的getType函数是私有的。如果不为类提供任何访问修饰符,则所有成员、变量和函数都是隐式私有的。

因此,您要么需要一个友元声明,要么将getType函数公开。

class Base {
public:
    virtual int getType() const = 0;
    bool operator ==(const Base &b) const {
        return getType() == b.getType();
    }
};
class Type1 : public Base {
public:
    virtual int getType() const {
        cout << "Type1.getType()" << endl;
        return 1;
    };
};
class Type2 : public Base {
public:
    virtual int getType() const {
        cout << "Type2.getType()" << endl;
        return 2;
    };
};

用法

Base *t1 = new Type1(), *t2 = new Type2();
bool res1 = *t1 == *t1; // true, calls Type1.getType() twice
bool res2 = *t1 == *t2; // false, calls Type1.getType() and Type2.getType()

是的,您可以在Base类中完成。这样做不会出错。

class Base{
    public:
        virtual int getType() const = 0;
        bool operator==(const Base& rhs) const{
                return getType() == rhs.getType();
        }
        bool operator!=(const Base& rhs) const{
                return !(*this == rhs);
        }
};