#include <iostream>
using namespace std;
class A {
public:
A() {
f(); // 构造函数中无运行时多态,输出A::f()
}
virtual void f() {
cout << "A::f()" << endl;
}
void g() {
cout << "A::g()" << endl;
}
virtual ~A() { // 将基类析构函数声明为virtual
cout << "des A" << endl;
f(); // 析构函数中有运行时多态
}
};
class B: public A {
public:
B() {
f(); // 构造函数中无运行时多态,输出A::f()
}
virtual void f() {
cout << "B::f()" << endl;
}
void g() {
cout << "B::g()" << endl;
}
~B() {
cout << "des B" << endl;
f(); // 析构函数中有运行时多态
}
};
int main() {
/**
* 输出:
* A::f()
* B::f()
*/
A *p = new B;
/**
* 输出:
* B::f()
*/
p->f();
/**
* 输出:
* A::g()
*/
p->g();
/**
* 输出:
* des B
* B::f()
* des A
* A::f()
*/
delete p;
}
输出结果:
A::f()
B::f()
B::f()
A::g()
des B
B::f()
des A
A::f()