使派生类使用重写运算符
Making derived class use overridden operator
我有以下代码:
#include <iostream>
using namespace std;
class Base {
public:
Base operator/(const Base& other){
Base res;
cout << "Base /" << endl;
return res;
}
Base& operator/=(const Base& other){
cout << "Base /=" << endl;
return *this;
}
};
class Derived : public Base {
public:
Derived operator/(const Derived& other){
Derived res;
cout << "Derived /" << endl;
return res;
}
};
int main() {
Derived d1, d2;
Base b1, b2;
b1 = d1 / d2;
b2 = d1 /= d2;
}
第二个赋值输出Base /=
。我可以在不覆盖operator/=
的情况下实现使用被覆盖operator/
的第二个分配吗?我想我必须使用另一个运算符实现一个运算符。
这是功课,所以只给出基本的想法是可以的。
虽然显然不是首选方式,而且可能是某种"丑陋",但可以在不提供Derived::operator/=
的情况下使用Derived::operator/
。为此,必须执行以下步骤:
- 在实现
Base::operator/=
时调用操作员/
- 使运算符
/
虚拟,使其不会静态绑定到/=
实现中 - 在类
Derived
中提供一个覆盖Base
中的operator/
实现,即除了Derived operator/(const Derived&)
之外,还提供运算符virtual Base operator/(const Base&)
(请注意,后者不能覆盖,因为它具有协变参数类型( - 在此
Derived::operator/(const Base& other)
-实现中,检查other
的动态类型并显式调用相应的实现。
请参阅以下代码:
class Base {
public:
virtual Base operator/(const Base& other) const {
Base res;
cout << "Base /" << endl;
return res;
}
Base& operator/=(const Base& other){
cout << "Base /=" << endl;
*this = *this / other;
return *this;
}
};
class Derived : public Base {
public:
virtual Base operator/(const Base& other) const override {
cout << "Derived /(Base&)" << endl;
if(dynamic_cast<const Derived*>(&other)==0) {
// do something specific here, or call base operator:
return Base::operator/(other);
}
else {
return operator/(dynamic_cast<const Derived&>(other));
}
}
Derived operator/(const Derived& other) const { // cannot override
cout << "Derived /(Derived&)" << endl;
return *this;
}
};
int main() {
Derived d1, d2;
Base b1, b2;
b1 = d1 / d2;
// Output: Derived /(Derived&)
b2 = d1 /= d2;
// Output:
// Base /=
// Derived /(Base&)
// Derived /(Derived&)
return 0;
}
请注意,表达式Derived d3 = d2 /= d1
仍然是不可能的,因为运算符Base& Base::operator /=
的返回类型 Base &
无法转换为 Derived &
。
相关文章:
- C++:从抽象类重写纯虚拟运算符重载
- 重写派生类中的二元运算符
- 将方法委托给成员的重写运算符>
- 通过运算符使用标量参数重写来修改类成员
- 重写自定义数组类的运算符/开始/结束
- 使用空实现重写删除运算符
- 使派生类使用重写运算符
- 试图重写代码以包括模量运算符
- 重写运算符 [] 和调用方法
- 将运算符重写应用于具有动态分配指针的类
- 如何在模板子类中重写转换运算符C++
- 重写运算符的返回类型=
- 重写C++中的类和运算符
- 重写迭代器的运算符*()
- Boost Python重写相等运算符
- 更正重写的QDataStream运算符和链接问题
- 类中调用的重写[]运算符的版本错误
- C++运算符重写
- 堆中的对象和重写索引运算符
- 重写String类中的下标运算符