【问题标题】:Why is initialization of derived class through a base class pointer different from that through a derived class pointer?为什么通过基类指针初始化派生类与通过派生类指针初始化不同?
【发布时间】:2015-03-04 12:02:56
【问题描述】:
#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”时,不应该初始化相同类型的对象,无论是来自基类指针还是派生类指针?

【问题讨论】:

  • 不是初始化不同。这是您通过指针访问非虚拟方法的事实。
  • @juanchopanza 你能详细说明一下吗?
  • 那是C++的设计——没有自动虚函数。
  • pBase 转换为Derived* 看看会发生什么。

标签: c++ inheritance polymorphism virtual-functions


【解决方案1】:

函数F()不是虚拟的,这意味着函数调用会被静态分派到指针/引用的静态类型中的版本,而不是让它在运行时发现对象的真正动态类型是什么是。

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

pDerived->Base::F();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2020-08-19
    • 2010-12-24
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多