已知Horse类是Pegasus类的父类,根据以下主函数完善程序内容,以实现规定的输出。不允许改变主函数的内容。
int main() { Horse *p1 = new Horse; //输出:Horse 申请了空间... Horse *p2 = new Pegasus; /* 输出两行: Horse 申请了空间... Pegasus 申请了空间... */ cout << endl; p1->Fly(); //输出:Just a horse. p2->Fly(); //输出:I can fly! cout << endl; delete p1; //输出:Horse 释放了空间... delete p2; /* 输出两行: Pegasus 释放了空间... Horse 释放了空间... */ return 0; }
输入格式:
无
输出格式:
根据样例格式输出。
输入样例:
在这里给出一组输入。例如:
无
输出样例:
在这里给出相应的输出。例如:
Horse 申请了空间... Horse 申请了空间... Pegasus 申请了空间... Just a horse. I can fly! Horse 释放了空间... Pegasus 释放了空间... Horse 释放了空间...
第一版的代码是:
#include <iostream> using namespace std; class Horse { public: Horse(){cout<<"Horse 申请了空间..."<<endl;} void Fly() {cout<<"Just a horse."<<endl;} ~Horse(){cout<<"Horse 释放了空间..."<<endl;} }; class Pegasus:public Horse { public: Pegasus() { cout<<"Horse 申请了空间..."<<endl; cout<<"Pegasus 申请了空间..."<<endl;} void Fly() {cout<<"I can fly!"<<endl;} ~Pegasus(){cout<<"Pegasus 释放了空间..."<<endl;} }; int main() { Horse *p1 = new Horse; //输出:Horse 申请了空间... Horse *p2 = new Pegasus; /* 输出两行: Horse 申请了空间... Pegasus 申请了空间... */ cout << endl; p1->Fly(); //输出:Just a horse. p2->Fly(); //输出:I can fly! cout << endl; delete p1; //输出:Horse 释放了空间... delete p2; /* 输出两行: Pegasus 释放了空间... Horse 释放了空间... */ return 0; }
但是这样的输出结果为
Horse 申请了空间... Horse 申请了空间... Horse 申请了空间... Pegasus 申请了空间... Just a horse. Just a horse. Horse 释放了空间... Horse 释放了空间...
“i can fly ”这行不对 以及“ Horse 申请了空间...” 多了一行
第二版改为
#include <iostream> using namespace std; class Horse { public: Horse(){cout<<"Horse 申请了空间..."<<endl;} virtual void Fly() {cout<<"Just a horse."<<endl;} virtual ~Horse(){cout<<"Horse 释放了空间..."<<endl;} }; class Pegasus:public Horse { public: Pegasus(){ cout<<"Pegasus 申请了空间..."<<endl;} void Fly() {cout<<"I can fly!"<<endl;} ~Pegasus(){cout<<"Pegasus 释放了空间..."<<endl;} }; int main() { Horse *p1 = new Horse; //输出:Horse 申请了空间... Horse *p2 = new Pegasus; /* 输出两行: Horse 申请了空间... Pegasus 申请了空间... */ cout << endl; p1->Fly(); //输出:Just a horse. p2->Fly(); //输出:I can fly! cout << endl; delete p1; //输出:Horse 释放了空间... delete p2; /* 输出两行: Pegasus 释放了空间... Horse 释放了空间... */ return 0; }
即可
关于virtual的用法-https://www.cnblogs.com/weiyouqing/p/7544988.html