#include<iostream>
#include<stdlib.h>
using namespace std;
#define PI 3.14
class Shape{
public:
Shape() :Area(0), Vol(0){};
virtual void getArea() = 0;
virtual void getVol() = 0;
void output(){
cout << "面积为" << Area << endl;
cout << "体积为" << Vol << endl;
}
protected:
double Area;
double Vol;
};
class Circle :public Shape{
public:
Circle(){
Radius = 0;
};
Circle(double radius) :Radius(radius){};
void getArea();
void getVol();
void setRadius(double radius);
protected:
double Radius;
};
void Circle::getArea(){
Area = PI*Radius*Radius;
}
void Circle::getVol(){
Vol = PI*Radius*Radius*Radius*4/3.0;
}
void Circle::setRadius(double radius){
Radius = radius;
}
class Rectange :public Shape{
public:
Rectange(){
Width = 0;
Length = 0;
Height = 0;
};
Rectange(double width, double length, double height) :Width(width), Height(height),Length(length){};
void getArea();
void getVol();
void setLength(double length);
void setWidth(double width);
void setHeight(double height);
void setAll(double width, double length, double height);
protected:
double Width;
double Height;
double Length;
};
void Rectange::getArea(){
Area = Width*Length;
}
void Rectange::getVol(){
Area = Width*Height*Length;
}
void Rectange::setWidth(double width){
Width = width;
}
void Rectange::setLength(double length){
Length = length;
}
void Rectange::setHeight(double height){
Height = height;
}
void Rectange::setAll(double width, double length, double height){
Width = width;
Length = length;
Height = height;
}
void OutputInformation(Shape *s)
{
s->getArea();
s->getVol();
s->output();
}
class Zhengfang:public Shape{
public:
Zhengfang(){
Bian = 0;
}
Zhengfang(double bian):Bian(bian){
}
void getArea()
{
Area = Bian*Bian;
}
void getVol()
{
Vol = Bian*Bian*Bian;
}
void setBian(double bian){
Bian = bian;
}
protected:
double Bian;
};
int main()
{
Shape *s = new Zhengfang(1);
OutputInformation(s);
system("pause");
}
设计多态这种类之间的关系的时候,切记不变提取,变则单独实现,不针对具体编程,针对接口编程,并针对最小接口编程