题目如下:
The code in the main() function is incomplete. Write code as described in each of the comments marked (1), (2) and (3) above. Your code for (2) and (3) should take advantage of polymorphism to keep the code simple and short.
我的解法如下:(虽然解出来了,感觉有点蠢,之前并没有用到过 static_cast )
重点是我觉得我的解法跟 polymorphism 多态好像没啥关系,是我的思路有问题吗?
#include <string>
#include <iostream>
using namespace std;
// class definition for Quadraped
class Quadruped{
protected:
int height; // height of the quadruped in hands
public:
Quadruped(int height); // constructor
int get_height(); // get the height
};
Quadruped::Quadruped(int hands){ // implementation of constructor
height=hands;
}
int Quadruped::get_height(){ // implementation of get_height
return height;
}
// ------------------------------------------------------------
// abstract class for Equines
class Equine:public Quadruped{
public:
Equine(int hands); // constructor
virtual void ride() =0; // not implemented here
};
// constructor
Equine::Equine(int hands):Quadruped(hands){
return; // nothing more to do
}
// ------------------------------------------------------------
class Horse:public Equine{
public:
Horse(int hands); // constructor
virtual void ride(); // will define
};
Horse::Horse(int hands):Equine(hands){
return; // nothing more to do
}
void Horse::ride(){
cout << "You ride off into the sunset" << endl;
}
// ------------------------------------------------------------
class Zebra:public Equine{
private:
int stripes;
public:
Zebra(int hands); // constructor
virtual void ride(); // will define
void setStripes(int strs);
int getStripes();
};
Zebra::Zebra(int hands):Equine(hands){
stripes=0;
return;
}
void Zebra::ride(){
cout << "The Zebra bites you and does not let go." << endl;
}
void Zebra::setStripes(int strs) {
stripes=strs;
}
int Zebra::getStripes() {
return(stripes);
}
// ------------------------------------------------------------
int main(){
//collection of assets
int num=4;
Quadruped* my_things[num];
// complete the code below
// (1) add two horses and two zebras to my_things, all of different heights.
for (int i = 0; i < num; i++) {
if (i < 2) {
my_things[i] = new Horse(100 + i * 10);
} else {
my_things[i] = new Zebra(100 + i * 10);
}
}
// (2) call ride on each of the items in my_things
Equine * temp[num] ;
for (int i = 0; i < num; ++i) {
temp[i] = static_cast<Equine *>(my_things[i]);
temp[i]->ride();
}
// (3) add code to set the number of stripes on any zebras to 13.
for (int i = 0; i < num; ++i) {
if (typeid(*temp[i]).name() == typeid(Zebra).name()) {
Zebra * temp_zebra = static_cast<Zebra*>(my_things[i]);
temp_zebra->setStripes(13);
cout << temp_zebra->getStripes() << endl;
}
}
// clean up
for (int i = 0; i < num ; ++i) {
delete temp[i];
}
}
以上代码输出结果如下( memcheck 没有内存泄漏):
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.