使用多态在C ++中重载==和!=运算符

时间:2016-05-08 06:40:12

标签: c++ polymorphism operator-overloading

这是事情。我有一个基类和4个子类。

pip install <module_name>

我需要重载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作为两个操作数,但是当我这样做时,当我在子视图上使用运算符时,我的IDE开始尖叫,它无法比较结构

所以问题是。有没有办法只需一次实现运算符而不必为每个子类组合指定它们?

谢谢!

3 个答案:

答案 0 :(得分:0)

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

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

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

因此,您需要一个朋友声明或公开getType函数。

答案 1 :(得分:0)

是的,您可以在 Base 类中执行此操作。这样做不会有任何错误。

&#xA;&#xA;
  class Base {&#xA;市民:&#XA; virtual int getType()const = 0;&#xA;&#xA; bool operator ==(const Base&amp; rhs)const {&#xA; return getType()== rhs.getType();&#xA; }&#XA;&#XA; bool operator!=(const Base&amp; rhs)const {&#xA; return!(* ​​this == rhs);&#xA; }&#XA;};&#XA;  
&#XA;

答案 2 :(得分:0)

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()