2

我正在尝试覆盖基类中另一个方法使用的基类方法;但是,当派生类调用基类的 using 方法时,派生的 used-method 永远不会执行,而是调用基类的 used-method。这是一个例子:

#include <iostream>
using namespace std;
class Base {
public:
    Base() {}
    virtual ~Base() {}
    void printLeft() { cout << this->getLeft(); }
    int getLeft() { return 0; }
};

class Derived: public Base {
public:
    Derived() {}
    virtual ~Derived() {}
    int getLeft() { return 1; }
};
int main(int argc, char *argv[]) {
    Derived d = Derived();
    d.printLeft();
}

运行main()prints 0,表明使用了Base'sgetLeft()方法而不是派生对象的方法。

当从 Derived 的实例Derived::getLeft()调用时,如何更改此代码?

4

2 回答 2

6

你只需要使getLeft虚拟:

class Base {
public:
    Base() {}
    virtual ~Base() {}
    void printLeft() { cout << this->getLeft(); }
    virtual int getLeft() { return 0; }
};

默认情况下,在 C++ 中,成员函数不是虚拟的。也就是说,您不能在子类中覆盖它们。

于 2012-05-15T16:02:33.503 回答
1

For non-virtual functions, the static type of the object is used to determine which class's method is called.

In your case, you are calling getLeft() from Base::printLeft(). The type of this is Base*, so the function called will be Base::getLeft().

The way around this is to use the virtual keyword. In that case, the virtual function table will be used to determine which version of getLeft() to call, in this case Derived.

You can trigger this behavior by prepending virtual to the declarations of printLeft in both Base and Derived.

于 2012-05-15T16:13:51.483 回答