定义一个 Shape 抽象类,在此基础上派生出 Rectangle 和 Circle,二者都有 GetArea()函数计算对象的面积,GetPerim()函数计算对象的周长。
Shape.h:
class Shape{
public:
Shape(){};
~Shape(){};
virtual double GetArea()=0;
virtual double GetPerim()=0;
};
class Rectangle:public Shape{
private:
double x,y,z;
public:
Rectangle(double x1,double y1,double z1):x(x1),y(y1),z(z1){};
Rectangle(){};
virtual double GetArea(){
double q=(x+y+z)/2.0;
return sqrt(q*(q-x)*(q-y)*(q-z));
};
virtual double GetPerim(){return x+y+z;};
};
class Circle:public Shape{
private:
double r;
public:
Circle(){};
Circle(double r1):r(r1){};
virtual double GetArea(){
return 3.14*r*r;
};
virtual double GetPerim(){ return 2*3.14*r;};
};
Main.cpp:
#include<iostream>
(720)#include<math.h>
#include"Shape.h"
using namespace std;
int main(){
double x,y,z,r;
cout<<"input x,y,z:";
cin>>x>>y>>z;
Shape *p=new Rectangle(x,y,z);
cout<<"Area:"<<p->GetArea()<<endl;
cout<<"Perim:"<<p->GetPerim()<<endl;
cout<<"input r:";
cin>>r;
p=new Circle(r);
cout<<"Area:"<<p->GetArea()<<endl;
cout<<"Perim:"<<p->GetPerim()<<endl;
return 0;
}
解:
源程序:
#include <iostream.h> class Shape { public: Shape(){} ~Shape(){} virtual float GetArea() =0 ; virtual float GetPerim () =0 ; }; class Circle : public Shape { public: Circle(float radius):itsRadius(radius){} ~Circle(){} float GetArea() { return 3.14 * itsRadius * itsRadius; } float GetPerim () { return 6.28 * itsRadius; } private: float itsRadius; }; class Rectangle : public Shape { public: Rectangle(float len, float width): itsLength(len), itsWidth(width){}; ~Rectangle(){}; virtual float GetArea() { return itsLength * itsWidth; } float GetPerim () { return 2 * itsLength + 2 * itsWidth; } virtual float GetLength() { return itsLength; } virtual float GetWidth() { return itsWidth; } private: float itsWidth; float itsLength; }; void main() { Shape * sp; sp = new Circle(5); out << "The area of the Circle is " << sp->GetArea () << endl; cout << "The perimeter of the Circle is " << sp->GetPerim () << endl; delete sp; sp = new Rectangle(4,6); cout << "The area of the Rectangle is " << sp->GetArea() << endl; cout << "The perimeter of the Rectangle is " << sp->GetPerim () << endl; delete sp; }程序运行输出:
The area of the Circle is 78.5
The perimeter of the Circle is 31.4
The area of the Rectangle is 24
The perimeter of the Rectangle is 20