题目描述
KiKi理解了继承可以让代码重用,他现在定义一个基类shape,私有数据为坐标点x,y, 由它派生Rectangle类和Circle类,它们都有成员函数GetArea()求面积。派生类Rectangle类有数据:矩形的长和宽;派生类Circle类有数据:圆的半径。Rectangle类又派生正方形Square类,定义各类并测试。输入三组数据,分别是矩形的长和宽、圆的半径、正方形的边长,输出三组数据,分别是矩形、圆、正方形的面积。圆周率按3.14计算。
输入描述:
输入三行,
第一行为矩形的长和宽,
第二行为圆的半径,
第三行为正方形的边长。
输出描述:
三行,分别是矩形、圆、正方形的面积。
话不多说,这次绝对是干货!!!
#include<iostream>
using namespace std;
typedef float ElemType;
#define PI 3.14f
class shape //基类
{
private:
ElemType x,y;
public:
shape(ElemType sum){
x=sum;
}
shape(ElemType sumX,ElemType sumY){
x=sumX; y=sumY;
}
ElemType GetX(){return x;}
ElemType GetY(){return y;}
virtual ElemType GetArea(){return 0;}
virtual void Print(){
cout<<GetArea()<<endl;
}
};
class Rectangle:public shape //矩形类(继承基类)
{
public:
Rectangle(ElemType sum):shape(sum){}
Rectangle(ElemType sumX,ElemType sumY):shape(sumX,sumY){}
ElemType GetArea(){
return GetX()*GetY();
}
void Print(){
shape::Print();
}
};
class Circle:public shape //圆形类(继承基类)
{
public:
Circle(ElemType sum):shape(sum){}
ElemType GetArea(){
return PI*GetX()*GetX();
}
void Print(){
shape::Print();
}
};
class Square:public Rectangle //正方形类(继承矩形类)
{
public:
Square(ElemType sum):Rectangle(sum){}
ElemType GetArea(){
return GetX()*GetX();
}
void Print(){
shape::Print();
}
};
int main()
{
ElemType x,y,r,a;
cin>>x>>y>>r>>a;
Rectangle re(x,y);
re.Print();
Circle cir(r);
cir.Print();
Square sq(a);
sq.Print();
return 0;
} PS:1.当基类存在某一函数,该函数在多个子类都存在时使用虚函数(大体功能相同) 2.在子类中可调用基类共有部分的任一变量(函数)

京公网安备 11010502036488号