virtual function call from base class(从基类调用虚函数)
问题描述
假设我们有:
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?
这篇关于从基类调用虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从基类调用虚函数
- C++指向数组的指针 1970-01-01
- 使用最流行的转义序列 1970-01-01
- C语言可使用的所有转义序列 1970-01-01
- 打印扩展的ASCII字符 1970-01-01
- 运算符优先级 1970-01-01
- “纯虚函数调用"在哪里?崩溃从何而来? 2022-10-18
- 使用来自float.h和limits的数据,找到该系统的一些 1970-01-01
- 使用整数值初始化char类型的变量 1970-01-01
- C语言求模 1970-01-01
- C++浮点常数 1970-01-01