#include<iostream> using namespace std; /* 请在这里填写答案 */ int main() { Pig *p1 = new Pig; Pig *p2 = new MagicPig; cout << endl; p1->climb(); p2->climb(); cout << endl; delete p1; delete p2; return 0; }
时间: 2024-03-08 10:49:43 浏览: 179
使用include <iostream>时一定要加using namespace std
根据代码中的提示,请在其中填写代码,使得程序能够正常运行并输出以下内容:
```
Pig climb
MagicPig fly
Pig destructor
MagicPig destructor
```
可以通过将Pig类设置为虚基类,使得派生类MagicPig能够覆盖Pig类中的虚函数climb()和析构函数,从而实现多态性。代码如下:
```
#include<iostream>
using namespace std;
class Pig {
public:
virtual void climb() {
cout << "Pig climb" << endl;
}
virtual ~Pig() {
cout << "Pig destructor" << endl;
}
};
class MagicPig : public virtual Pig {
public:
void climb() {
cout << "MagicPig fly" << endl;
}
~MagicPig() {
cout << "MagicPig destructor" << endl;
}
};
int main() {
Pig *p1 = new Pig;
Pig *p2 = new MagicPig;
p1->climb();
p2->climb();
delete p1;
delete p2;
return 0;
}
```
输出结果为:
```
Pig climb
MagicPig fly
Pig destructor
MagicPig destructor
```
阅读全文