定义一个抽象类Element,提供显示,求面积等公共接口(纯虚函数),然后派生出Point,Line,Circle等图形元素类,并定义这些虚函数!
程序代码:
#include<iostream>
#include<cmath>
using namespace std;
const double PI = 3.14159;
class Element{
public:
virtual void Show()const=0;
virtual double Area()const=0;
};
class Point:public Element{
protected:
double x,y;
public:
Point(): x(0), y(0) {}
Point(double x, double y): x(x), y(y) {}
void Show()const {
cout << "x=" << x << ' ' << "y=" << y << endl;
}
double Area()const {
return 0;
}
double Getx()const {
return x;
}
double Gety()const {
return y;
}
};
class Circle:public Point{
protected:
double radius;
public:
Circle(): radius(0) {}
Circle(double x,double y,double r):Point (x,y){
radius = r;
}
Circle(const Circle &cir):Point (cir){
radius = cir.radius;
}
void Show()const {
Point::Show();
cout << "radius=" << radius << endl;
}
double Area ()const {
return PI * radius * radius;
}
};
class Line:public Element{
protected:
Point start,end;
public:
Line() {}
Line(double xv1, double yv1, double xv2, double yv2): start(xv1, yv1), end(xv2, yv2) {}
double Area()const {
return 0;
}
void Show()const {
cout << "start point :\n";
start.Show();
cout << "end point\n";
end.Show();
}
double GetLenth()const {
double dx, dy;
dx = start.Getx() - end.Getx();
dy = start.Gety() - end.Gety();
return sqrt(dx * dx + dy * dy);
}
};
main函数的书写有讲究得重点突出基类指针指向派生类对象,并调用函数!
int main(){
Element *p;
Point point(3,4);
Circle C(100,100,10);
Line ln(0,0,100,100);
p=&point;
p->Show();
cout<<"点面积"<<p->Area()<<endl;
p=&C;
p->Show();
cout<<"圆面积"<<p->Area()<<endl;
p=&ln;
p->Show();
cout << "线面积:" << p->Area()<< endl
<< "线长度:" << ln.GetLenth()<<endl;
return 0;
}
注意,GetLenth()函数不是抽象类中的成员函数;调用不能用基类指针调用!
有收获的小伙伴别忘了点关注哦!