(1)人与复读机
#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)复读机的毁灭
#include <iostream>
using namespace std;
/********* Begin *********/
class Repeater
{
//复读机基类的声明
public:
virtual void Play();
virtual ~Repeater();
};
//复读机基类的定义
void Repeater::Play()
{
}
Repeater::~Repeater()
{
cout<<"砰!"<<endl;
}
class ForRepeater : public Repeater
{
//正向复读机的声明
public:
void Play() ;
~ForRepeater();
};
//正向复读机的定义
void ForRepeater::Play()
{
cout<<"没想到你也是一个复读机"<<endl;
}
ForRepeater::~ForRepeater()
{
cout<<"正·复读机 炸了"<<endl;
}
class RevRepeater : public Repeater
{
//反向复读机的声明
public:
void Play() ;
~RevRepeater();
};
//反向复读机的定义
void RevRepeater::Play()
{
cout<<"机读复个一是也你到想没"<<endl;
}
RevRepeater::~RevRepeater()
{
cout<<"机读复·反 炸了"<<endl;
}
//普通函数
Repeater* CreateRepeater(int type)
{
//根据type创建指定的复读机
Repeater *p;
if(type==0)
{
p=new ForRepeater;
}
else
{
p=new RevRepeater;
}
}
/********* End *********/
(3)计算图像面积
#include <iostream>
using namespace std;
/********* Begin *********/
class Shape
{
//基类的声明
public:
virtual void PrintArea() = 0;
};
class Rectangle : public Shape
{
//矩形类的声明
public:
float H,W;
void PrintArea();
Rectangle(float w,float h);
};
//矩形类的定义
void Rectangle::PrintArea()
{
cout<<"矩形面积 = "<<H*W<<endl;
}
Rectangle::Rectangle(float w,float h)
{
W = w;
H = h;
}
class Circle : public Shape
{
//圆形类的声明
public:
float R;
void PrintArea();
Circle(float r);
};
void Circle::PrintArea()
{
cout<<"圆形面积 = "<<3.14*R*R<<endl;
}
Circle::Circle(float r)
{
R=r;
}
//圆形类的定义
/********* End *********/