写一个程序,定义抽象基类Shape,由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。
#include<iostream>
using namespace std;
class Shape
{
public:
virtual float printArea() const {return 0.0;};
};
class Circle:public Shape
{
public:
Circle(float =0);
virtual float printArea() const {return 3.14159*radius*radius;}
protected:
float radius;
};
Circle::Circle(float r):radius(r)
{
}
class Rectangle:public Shape
{
public:
Rectangle(float =0,float =0);
virtual float printArea() const;
protected:
float height;
float width;
};
Rectangle::Rectangle(float w,float h):width(w),height(h){
}
float Rectangle::printArea()const
{
return width*height;
}
class Triangle:public Shape
{
public:
Triangle(float =0,float =0);
virtual float printArea() const;
protected:
float height;
float width;
};
Triangle::Triangle(float w,float h):width(w),height(h){
}
float Triangle::printArea()const
{
return 0.5*width*height;
}
void printArea(const Shape&s)
{
cout<<s.printArea()<<endl;
}
int main()
{
Circle circle(12.6);
cout<<"area of circle=";
printArea(circle);
Rectangle rectangle(4.5,8.4);
cout<<"area of rectangle=";
printArea(rectangle);
Triangle triangle(4.5,8.4);
cout<<"area of triangle=";
printArea(triangle);
}
用基类指针数组,使它每个元素指向一个派生类对象,求面积之和。
Shape *p[3]={&circle,&rectangle,&triangle};
double area=0.0;
for(int i=0;i<3;i++)
{
area+=p[i]->printArea();
}
cout<<"total of all area= "<<area;
area of circle=498.759
area of rectangle=37.8
area of triangle=18.9
total of all area= 555.459
--------------------------------
Process exited after 0.4691 seconds with return value 0
请按任意键继续. . .