【Educoder作业】C++ 面向对象 - 类的多态性与虚函数
这个就是知道 v i r t u a l virtual virtual就会了。
T1 人与复读机
有了虚函数就可以实现派生类的多态性了。
#include <iostream>
using namespace std;
/********* Begin *********/
class Chinese
{
//人类的声明
public :
virtual void greet() {
puts("你好");
}
};
//人类的定义
class EnglishLearner : public Chinese
{
//英语学生类的声明
public :
void greet();
};
//英语学生类的定义
void EnglishLearner :: greet() {
puts("Hello");
}
class Repeater : public Chinese
{
//复读机类的声明
public :
void greet();
};
//复读机类的定义
void Repeater :: greet() {
Chinese :: greet();
}
/********* End *********/
T2 复读机的毁灭
重写的时候,我们可以加一个 o v d e r r i d e ovderride ovderride告诉计算机我们要重写这个类的这个函数了。
#include <iostream>
using namespace std;
/********* Begin *********/
class Repeater
{
//复读机基类的声明
public :
virtual void Play() {
}
virtual ~Repeater() {
puts("砰!");
}
};
//复读机基类的定义
class ForRepeater : public Repeater
{
//正向复读机的声明
public :
void Play() override;
~ForRepeater() {
puts("正·复读机 炸了");
}
};
//正向复读机的定义
void ForRepeater :: Play() {
puts("没想到你也是一个复读机");
}
class RevRepeater : public Repeater
{
//反向复读机的声明
public :
void Play() {
puts("机读复个一是也你到想没");
}
~RevRepeater() {
puts("机读复·反 炸了");
}
};
//反向复读机的定义
//普通函数
Repeater* CreateRepeater(int type)
{
//根据type创建指定的复读机
Repeater *re;
if (type == 0) {
re = new ForRepeater;
return re;
}
else if (type == 1) {
re = new RevRepeater;
return re;
}
return 0;
}
/********* End *********/
T3 计算图像面积
如果这个派生类的多态性的实现,并没有继承的含义在里面。也就是多态之间没什么交集,只不过有一个这样的基类而已。我们就整一个抽象类就行了,不需要实现具体的虚函数。
#include <iostream>
using namespace std;
/********* Begin *********/
class Shape
{
//基类的声明
public :
virtual void PrintArea() = 0;
};
class Rectangle : public Shape
{
//矩形类的声明
public :
void PrintArea();
Rectangle(float w, float h) {
width = w, height = h;}
float width, height;
};
//矩形类的定义
void Rectangle :: PrintArea() {
cout << "矩形面积 = " << width * height << endl ;
}
class Circle : public Shape
{
//圆形类的声明
public :
void PrintArea();
Circle(float r) {
radio = r;}
float radio;
};
//圆形类的定义
void Circle :: PrintArea() {
cout << "圆形面积 = " << radio * radio * 3.14 << endl ;
}
/********* End *********/