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?
这篇关于从基类调用虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从基类调用虚函数
基础教程推荐
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- C++按值调用 1970-01-01
- 初始化变量和赋值运算符 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- C++ #define 1970-01-01
- C语言访问数组元素 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++定义类对象 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01