简体   繁体   English

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

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

Here is the thing.这是事情。 I have one base class and 4 child classes.我有一个基类和 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;
    };
};

I need to overload the == and != operators which do the same thing for all child classes, just retrieve the type values and compare them.我需要重载==!=运算符,它们对所有子类执行相同的操作,只需检索类型值并比较它们。 So I would naturally implement the operator in the Base class with references to Base as both operands but when I do that, my IDE starts screaming when I use the operators on child views, that it cannot compare structs.所以,我自然会实现在运营商Base一起引用类Base作为两个操作数,但是当我这样做,我的IDE开始尖叫,当我使用运营商的子视图,它不能比较结构。

So the question is.所以问题是。 Is there a way I can implement the operators just once without having to specify them for each combination of child classes ?有没有一种方法可以实现运算符一次,而不必为每个子类组合指定它们?

Thanks!谢谢!

I do not have any problem with this operator:我对这个运营商没有任何问题:

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

unless with an accessibility issue: Your getType function is private.除非有可访问性问题:您的 getType 函数是私有的。 If you do not provide any access modifier with classes, all members, variables and functions, are implicitly private.如果您没有为类提供任何访问修饰符,则所有成员、变量和函数都是隐式私有的。

So you either need a friend declaration or make the getType function public.因此,您要么需要友元声明,要么将 getType 函数设为公开。

Yes, you can do it in your Base class.是的,你可以在你的Base类中做到这一点。 There will be no error for doing this.这样做不会出错。

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;
    };
};

Usage :用法

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