OJ:析构函数实现多态

时间:2023-03-08 21:10:10

Description

下面程序的输出结果是:

destructor B

destructor A

请完整写出 class A。 限制条件:不得为 class A 编写构造函数。

#include <iostream>
using namespace std; class A {
// Your Code Here
}; class B:public A {
public:
~B() { cout << "destructor B" << endl; }
}; int main() {
A * pa;
pa = new B;
delete pa;
return 0;
}

实现代码

#include <iostream>
using namespace std; class A {
public:
virtual ~A() { cout << "destructor A" << endl; }
}; class B:public A {
public:
~B() { cout << "destructor B" << endl; }
}; int main() {
A * pa;
pa = new B;
delete pa; return 0;
}