C++知识:定义一个抽象类shape应以计算面积,
C++知识:定义一个抽象类shape应以计算面积,从中派生出计算长方形,梯形,圆形面积的派生类,程序中通过基类有指针来调用派生类中的虚函数,计算不同形状的面积。...
C++知识:定义一个抽象类shape应以计算面积,从中派生出计算长方形,梯形,圆形面积的派生类,程序中通过基类有指针来调用派生类中的虚函数,计算不同形状的面积。
展开
1个回答
展开全部
#include<iostream>
using namespace std;
class Shape //抽象基类
{
protected:
double s;
public:
Shape(){s=0;} //构造函数
virtual double Area() = 0; //面积计算函数(纯虚函数)
};
class Rect:public Shape //派生类——矩形
{
private:
double width;
double height;
public:
Rect(double w,double h) //构造函数
{
width=w; //宽
height=h; //高
}
double Area() //面积计算函数(实现)
{
s=width*height;
return s;
}
};
class Circle:public Shape //派生类亩手——圆形
{
private:
double radius; //半径
public:
Circle(double r){radius=r;} //构造函数
double Area() //面积计算函数(实现)
{
s=3.14159*radius*radius;
return s;
}
};
class Trapezium:public Shape //派生类——梯形凳耐乱
{
private:
double top; //上底
double bottom; //下底
double height; //高
public:
Trapezium(double t,double b,double h) //构造函数
{
top=t;
bottom=b;
height=h;
}
double Area() //面积计算函数(实现)
{
s=(top+bottom)*height/2;
return s;
}
};
void main()
{
Shape *pShape; //声明抽象基类指针
Rect rect(3,5);
Circle circle(4);
Trapezium trapezium(3.5,5.5,7);
pShape = ▭ //抽象基类指针指向枣档矩形
cout<<"矩形面积:"<<pShape->Area()<<endl;
pShape = &circle; //抽象基类指针指向圆形
cout<<"圆形面积:"<<pShape->Area()<<endl;
pShape = &trapezium; //抽象基类指针指向梯形
cout<<"梯形面积:"<<pShape->Area()<<endl;
}
using namespace std;
class Shape //抽象基类
{
protected:
double s;
public:
Shape(){s=0;} //构造函数
virtual double Area() = 0; //面积计算函数(纯虚函数)
};
class Rect:public Shape //派生类——矩形
{
private:
double width;
double height;
public:
Rect(double w,double h) //构造函数
{
width=w; //宽
height=h; //高
}
double Area() //面积计算函数(实现)
{
s=width*height;
return s;
}
};
class Circle:public Shape //派生类亩手——圆形
{
private:
double radius; //半径
public:
Circle(double r){radius=r;} //构造函数
double Area() //面积计算函数(实现)
{
s=3.14159*radius*radius;
return s;
}
};
class Trapezium:public Shape //派生类——梯形凳耐乱
{
private:
double top; //上底
double bottom; //下底
double height; //高
public:
Trapezium(double t,double b,double h) //构造函数
{
top=t;
bottom=b;
height=h;
}
double Area() //面积计算函数(实现)
{
s=(top+bottom)*height/2;
return s;
}
};
void main()
{
Shape *pShape; //声明抽象基类指针
Rect rect(3,5);
Circle circle(4);
Trapezium trapezium(3.5,5.5,7);
pShape = ▭ //抽象基类指针指向枣档矩形
cout<<"矩形面积:"<<pShape->Area()<<endl;
pShape = &circle; //抽象基类指针指向圆形
cout<<"圆形面积:"<<pShape->Area()<<endl;
pShape = &trapezium; //抽象基类指针指向梯形
cout<<"梯形面积:"<<pShape->Area()<<endl;
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询