web*_*rc2 2 c++ polymorphism inheritance
我试图覆盖基类中另一个方法使用的基类的方法; 但是,当派生类调用基类的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();
}
Run Code Online (Sandbox Code Playgroud)
运行main()打印0,指示使用Base的getLeft()方法而不是派生对象的方法.
如何更改此代码,以便在从Derived实例Derived::getLeft()调用时调用?
你只需要getLeft虚拟:
class Base {
public:
Base() {}
virtual ~Base() {}
void printLeft() { cout << this->getLeft(); }
virtual int getLeft() { return 0; }
};
Run Code Online (Sandbox Code Playgroud)
默认情况下,在C++中,成员函数不是虚拟的.也就是说,您不能在子类中覆盖它们.