#include <iostream>
using namespace std;
class Base {
public:
void F(){cout << "Base::F" << endl;};
virtual void G(){cout << "Base::G" << endl;};
};
class Derived : public Base {
public:
void F(){cout << "Derived::F" << endl;};
void G(){cout << "Derived::G" << endl;};
};
int main(){
Derived *pDerived = new Derived;
pDerived->F(); //F was redefined
pDerived->G(); //G was overriden
Base *pBase = new Derived;
pBase->F();
pBase->G();
}
此代码的输出为:
Derived::F
Derived::G
Base::F
Derived::G
为什么代码不能产生以下输出?
Derived::F
Derived::G
Derived::F
Derived::G
即。当通过基类指针初始化派生类对象时,为什么非虚函数的函数定义与通过派生类指针初始化的派生类对象的函数定义不同?当我们调用&#34; new Derived&#34;时,不应该初始化相同类型的对象。它是来自基类指针还是派生类指针?
答案 0 :(得分:4)
函数F()
不是虚拟的,这意味着函数调用将静态调度到指针/引用的静态类型中的版本,而不是让它在运行时找到动态类型的对象真的是。
如果您符合您感兴趣的变体,则可以从指向Derived
的指针访问相同的功能:
pDerived->Base::F();