为什么通过基类指针初始化派生类与通过派生类指针初始化不同
Why is initialization of derived class through a base class pointer different from that through a derived class pointer?
#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();
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 如何使用基类指针引用派生类成员
- 将派生指针分配给C 中的其他派生类型
- 如何通过派生指针调用基类中的模板成员函数
- 如何将带有恒定指针作为参数的模板的派生指针使用
- 无法返回包含派生指针的向量
- 如何创建派生指针类变量
- C++强制转换为派生指针或设计错误
- 无法从派生指针访问公共基成员
- C++发送派生指针作为参数
- 将专用基指针强制转换为专用于其他模板参数的派生指针("adding on"专用化)
- 在派生指针上显式调用基类析构函数时编译错误
- 安全派生指针值的示例
- 安全派生指针的整数表示形式
- c++多态克隆:如何从基指针获得派生指针
- 如果我将派生指针转换为基指针,这两个指针是否保证具有相同的值?
- 以任何方式将基指针强制转换为派生指针是否危险
- 将派生指针隐式强制转换为其相应基类的引用
- 当派生指针仅添加方法时,将基指针强制转换为派生指针的有效性
- c++转换指针到派生指针到基指针的例子