C++(继承)
#include <iostream>
#include<string>
#include<math.h>
using namespace std;
//抽象基类
class Shape{
protected:
string name;
public:
Shape(string name){
this->name=name;
}
void setName(string name){
this->name=name;
}
string getName()const{
return name;
}
//纯虚函数
virtual double getArea()const=0;
};
class Circle :public Shape{
private:
double radius;
public:
Circle(string name,double radius):Shape (name){
this->radius=radius;
}
void setRadius(double radius){
this->radius=radius;
}
double getRadius()const{
return radius;
}
virtual double getArea()const{
return 3.14*pow(radius,2);
}
};
class Rectangle:public Shape{
double length;
double width;
public:
Rectangle(string name,double length,double width):Shape(name){
this->length=length;
this->width=width;
}
void setLength(double width){
this->width=width;
}
void setWidth(double length){
this->length=length;
}
double getLength()const{
return length;
}
double getWidth()const{
return width;
}
virtual double getArea()const{
return length*width;
}
};
class Triangle:public Shape{
double base;
double width;
public:
Triangle(string name,double base,double width):Shape(name){
this->base=base;
this->width=width;
}
virtual double getArea()const{
return .5*base*width;
}
};
int main(){
/*第一种方式 打印面积*/
// Shape shape("shape");
//cout<<shape.getName()<<endl;
puts("****************************************");
Circle cycle("Circle",3.4);
cycle.setName("Circle too");
cout<<cycle.getName()<<endl;
cout<<cycle.getRadius()<<endl;
cout<<cycle.getArea()<<endl;
puts("****************************************");
Rectangle rectangle("Rectangle",4.3,2.3);
cout<<rectangle.getName()<<endl;
cout<<rectangle.getLength()<<endl;
cout<<rectangle.getWidth()<<endl;
cout<<rectangle.getArea()<<endl;
puts("****************************************");
Triangle triangle("triangle",4,3);
cout<<triangle.getArea()<<endl;
putchar(10);
/*第二种方式 打印面积*/
Shape*shapes[3]={
new Circle("Circle",3.4),
new Rectangle ("Rectangle",4.3,2.3),
new Triangle ("triangle",4,3)
};
for (int i = 0; i < 3; ++i) {
cout<<"Shape"<<i<<"\tarea:\t"<<shapes[i]->getArea()<<endl;
}
return 0;
}
posted on 2019-01-04 21:30 Indian_Mysore 阅读(96) 评论(0) 编辑 收藏 举报