过载==和!=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函数公开。
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);
}
};
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 运行时多态性 - 箭头运算符访问了错误的成员?
- 将多态性与运算符 + 重载模板化类结合使用.如何实现基类?
- 具有虚拟赋值运算符的多态性
- 如何用复数和多态性重载运算符
- 正确执行运算符重载和多态性
- 类多态性和相等运算符
- 过载==和!=C++中具有多态性的运算符
- 动态多态性和运算符重载的真实示例
- C++运算符重载和多态性
- C++:多态性和运算符重载
- c++中的多态性和运算符重载混淆
- 重载运算符[]多态性
- C++强制运算符重载和多态性