返回对"this"的取消引用的重写方法

Override method which returns dereference to "this"

本文关键字:重写 方法 引用 取消 this 返回      更新时间:2023-10-16

我在Base类中有一个方法,它返回对this的取消引用。我想在Derived类中使用此方法,但也对其进行了一点扩展。这个例子不言自明:

#include <iostream>
class Base {
   private:
    int value = 0;
   public:
    int getValue() { return value; }
    virtual Base& increase() {
        value++;
        return *this;
    }
};
class Derived : public Base {
   public:
    Derived& increase() {
        Base::increase();
        if (getValue() == 1) std::cout << "Success" << std::endl;
        return *this;
    }
};

据我了解,在上面的实现中,Base::increase();只会在临时分配的Base对象中增加一些value。我该如何解决它?

Base::increase(); this上调用基方法(不涉及临时对象)。

如果你更清楚,你甚至可以这样写

this->Base::increase();