为什么通过基类指针初始化派生类与通过派生类指针初始化不同

Why is initialization of derived class through a base class pointer different from that through a derived class pointer?

本文关键字:派生 指针 初始化 基类 为什么      更新时间:2023-10-16
#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
即,当派生类对象通过基类指针

初始化时,为什么非虚函数的函数定义与通过派生类指针初始化的派生类对象的函数定义不同?当我们调用"new Derived"时,无论是来自基类指针还是派生类指针,是否应该初始化相同类型的对象?

函数

F()不是虚拟的,这意味着函数调用将被静态调度到指针/引用的静态类型的版本,而不是让它在运行时找到对象的动态类型到底是什么。

您可以从指向Derived的指针访问相同的函数,如果您限定了您感兴趣的变体:

pDerived->Base::F();