为什么通过基 class 指针初始化派生 class 与通过派生 class 指针初始化不同?
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
即当派生class对象通过基class指针初始化时,为什么非虚函数的函数定义与通过派生[=]初始化的派生class对象的函数定义不同13=]指针?当我们调用 "new Derived" 时,无论是来自基 class 指针还是派生 class 指针,不应该初始化相同类型的对象吗?
函数F()
不是虚函数,这意味着函数调用将被静态调度到pointer/reference静态类型的版本,而不是让它在运行时查找什么确实是动态类型的对象。
如果您确定感兴趣的变体,则可以从指向 Derived
的指针访问相同的函数:
pDerived->Base::F();
#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
即当派生class对象通过基class指针初始化时,为什么非虚函数的函数定义与通过派生[=]初始化的派生class对象的函数定义不同13=]指针?当我们调用 "new Derived" 时,无论是来自基 class 指针还是派生 class 指针,不应该初始化相同类型的对象吗?
函数F()
不是虚函数,这意味着函数调用将被静态调度到pointer/reference静态类型的版本,而不是让它在运行时查找什么确实是动态类型的对象。
如果您确定感兴趣的变体,则可以从指向 Derived
的指针访问相同的函数:
pDerived->Base::F();