繁体   English   中英

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

[英]Overloading == and != operators in C++ with polymorphism

这是事情。 我有一个基类和 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 函数设为公开。

是的,你可以在你的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);
        }
};
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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM