第1关:人与复读机
任务描述
本关任务:设计人类、英语学生类和复读机类三个类。
相关知识
为了完成完成本关任务,你需要掌握虚函数的基本使用。
多态性
在面向对象的方法中,多态性是指向不同对象发送同一个消息,不同对象在接收时会产生不同的行为(方法)。
通俗点说就是可以不用像 C 语言中为了求多种图形的面积而针对不同的图形各设计一个独立名字的函数,在 C++ 中只要设计一个专门用于求面积的函数名即可。这个专门用于求面积的函数名可以作为各种求图形面积的函数名。
这么做的好处在于程序设计者可以省去设立多个函数名对应多个函数的麻烦,使用的时候统一用同一个函数名就可调用具有不同功能的函数。
多态在 C++ 中的实现可以是函数的重载、运算符的重载和虚函数,本实训我们介绍虚函数的使用。
#include <iostream>
using namespace std;
/********* Begin *********/
class Chinese
{
//人类的声明
public:
virtual void greet();
};
//人类的定义
void Chinese::greet(){
cout<<"你好"<<endl;
}
class EnglishLearner : public Chinese
{
//英语学生类的声明
public:
void greet() override;
};
//英语学生类的定义
void EnglishLearner::greet(){
cout<<"Hello"<<endl;
}
class Repeater : public Chinese
{
//复读机类的声明
public:
void greet() override;
};
//复读机类的定义
void Repeater:: greet(){
Chinese::greet();
}
/********* End *********/
第2关:复读机的毁灭
任务描述
本关任务:设计三个复读机类并实现一个普通函数。
相关知识
为了完成本关任务,你需要掌握虚析构函数的使用。
多态性的体现
C++ 允许将一个对象的指针赋值给它的父类指针变量。而当通过父类指针调用一个虚函数时,则会调用子类中最后被重写的那个版本,这样对于同一段通过指针调用某个虚函数的代码,就会因为实际指向的对象不同,而调用不同函数,这就是所谓的多态性。
同理,通过引用调用一个虚函数,也会有这样的效果。
#include <iostream>
using namespace std;
/********* Begin *********/
class Repeater
{
public:
virtual void Play(){};
virtual ~Repeater();
};
Repeater::~Repeater(){
cout<<"砰!"<<endl;
}
class ForRepeater : public Repeater
{
public:
void Play(){
cout<<"没想到你也是一个复读机"<<endl;
}
~ForRepeater(){
cout<<"正·复读机 炸了"<<endl;}
};
class RevRepeater : public Repeater
{
public:
void Play(){
cout<<"机读复个一是也你到想没"<<endl;
}
~RevRepeater(){
cout<<"机读复·反 炸了"<<endl;}
};
//反向复读机的定义
Repeater* CreateRepeater(int type)
{
Repeater *r;
if(type==0){
r=new ForRepeater;
}
else if(type==1){
r=new RevRepeater;
}else{
return 0;
}
}
/********* End *********/
第3关:计算图像面积
任务描述
本关任务:设计一个矩形类、一个圆形类和一个图形基类,计算并输出相应图形面积。
相关知识
为了完成本关任务,你需要掌握纯虚函数和抽象类的使用。
纯虚函数
有时在类中将某一成员声明为虚函数,并不是因为基类本身的要求,而是因为派生类的需求,在基类中预留一个函数名,具体功能留给派生类区定义。这种情况下就可以将这个纯虚函数声明为纯虚函数。即纯虚函数的作用是在基类中为其派生类保留一个函数的名字,以便派生类对它进行定义。
纯虚函数就是在声明虚函数时被初始化为0的函数,但它只有名字,不具备函数功能,不能被调用
#include <iostream>
using namespace std;
/********* Begin *********/
class Shape
{
//基类的声明
public:
virtual void PrintArea() = 0;
};
class Rectangle : public Shape
{
//矩形类的声明
public:
float hight,withd;
void PrintArea();
Rectangle(float w,float h);
};
//矩形类的定义
void Rectangle::PrintArea(){
cout<<"矩形面积 = "<<withd*hight<<endl;
}
Rectangle::Rectangle(float w,float h){
hight=h;
withd=w;
}
class Circle : public Shape
{
public:
float radio;
void PrintArea();
Circle(float r);
};
//圆形类的定义
void Circle::PrintArea(){
cout<<"圆形面积 = "<<radio*radio*3.14<<endl;
}
Circle::Circle(float r){
radio=r;
}
/********* End *********/