从基类调用虚函数
假设我们有:
Class Base
{
virtual void f(){g();};
virtual void g(){//Do some Base related code;}
};
Class Derived : public Base
{
virtual void f(){Base::f();};
virtual void g(){//Do some Derived related code};
};
int main()
{
Base *pBase = new Derived;
pBase->f();
return 0;
}
将从 Base::f()
调用哪个 g()
?Base::g()
还是 Derived::g()
?
Which g()
will be called from Base::f()
? Base::g()
or Derived::g()
?
谢谢...
推荐答案
会调用派生类的g.如果要调用base中的函数,调用
The g of the derived class will be called. If you want to call the function in the base, call
Base::g();
相反.如果您想调用派生版本,但仍希望调用基础版本,请安排 g 的派生版本在其第一条语句中调用基础版本:
instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement:
virtual void g() {
Base::g();
// some work related to derived
}
模板方法设计模式中使用了来自基类的函数可以调用虚方法并将控制权转移到派生类的事实.对于 C++,它被称为 Non-Virtual-Interface.它在 C++ 标准库中也被广泛使用(例如,C++ 流缓冲区有函数 pub...
调用执行实际工作的虚函数.例如 pubseekoff
调用受保护的seekoff
).我在这个答案中写了一个例子:你如何验证对象的内部状态?
The fact that a function from the base can call a virtual method and control is transferred into the derived class is used in the template method design pattern. For C++, it's better known as Non-Virtual-Interface. It's widely used also in the C++ standard library (C++ stream buffers for example have functions pub...
that call virtual functions that do the real work. For example pubseekoff
calls the protected seekoff
). I wrote an example of that in this answer: How do you validate an object’s internal state?
相关文章