使派生类使用重写运算符

Making derived class use overridden operator

本文关键字:运算符 重写 派生      更新时间:2023-10-16

我有以下代码:

#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/。为此,必须执行以下步骤:

  1. 在实现Base::operator/=时调用操作员/
  2. 使运算符/虚拟,使其不会静态绑定到/=实现中
  3. 在类Derived中提供一个覆盖Base中的operator/实现,即除了Derived operator/(const Derived&)之外,还提供运算符virtual Base operator/(const Base&)(请注意,后者不能覆盖,因为它具有协变参数类型(
  4. 在此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 &