[英]c++ make the base class use overridden methods in the child class
I'm trying to override a method of the base class used by another method in the base class; 我试图覆盖基类中的另一个方法所使用的基类方法; however, when the derived class invokes the using-method of the base class, the derived used-method is never executed, but instead the base class's used-method is called.
但是,当派生类调用基类的use-method时,将永远不会执行派生的used-method,而是调用基类的used-method。 Here's an example:
这是一个例子:
#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();
}
Running main()
prints 0
, indicating Base
's getLeft()
method was used rather than the derived object's method. 运行
main()
显示0
,表明使用了Base
的getLeft()
方法,而不是派生对象的方法。
How can I change this code so Derived::getLeft()
is called when called from an instance of Derived ? 我如何更改此代码,以便从Derived实例调用
Derived::getLeft()
时被调用 ?
You just need to make getLeft
virtual: 您只需要使
getLeft
虚拟:
class Base {
public:
Base() {}
virtual ~Base() {}
void printLeft() { cout << this->getLeft(); }
virtual int getLeft() { return 0; }
};
By default in C++ , member functions are not virtual. 在C ++中,默认情况下,成员函数不是虚拟的。 That is, you can't override them in a subclass.
也就是说,您不能在子类中覆盖它们。
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()
. 在你的情况,你在呼唤
getLeft()
从Base::printLeft()
The type of this
is Base*
, so the function called will be Base::getLeft()
. 该类型的
this
是Base*
,所谓的功能将Base::getLeft()
The way around this is to use the virtual
keyword. 解决此问题的方法是使用
virtual
关键字。 In that case, the virtual function table will be used to determine which version of getLeft()
to call, in this case Derived.
在这种情况下,虚拟函数表将用于确定要调用的
getLeft()
版本,在这种情况下为Derived.
You can trigger this behavior by prepending virtual
to the declarations of printLeft
in both Base
and Derived
. 您可以通过在
Base
和Derived
的printLeft
声明前添加virtual
来触发此行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.