C++面向对象类的实例题目十一
2024-10-20 11:36:20
题目描述:
写一个程序计算三角形,正方形和圆形3种图形的面积
程序代码:
#include<iostream>
#include<cmath>
#define PAI 3.1415
using namespace std;
class Shape
{
public:
virtual float area() //定义一个求面积的成员函数
{
return 0;
}
virtual void ShapeName() = 0;//定义一个纯虚函数
};
class Triangle:public Shape
{
public:
Triangle(float x,float y,float z):a(x),b(y),c(z){};
void ShapeName()
{
cout<<"Triangle:"<<endl;
}
float area()
{
float p = (a+b+c)/2;
float s = sqrt(p*(p-a)*(p-b)*(p-c));
return s;
}
private:
float a,b,c;
};
class Square:public Shape
{
public:
Square(float l):length(l){};
void ShapeName()
{
cout<<"Square:"<<endl;
}
float area()
{
float s = length * length;
return s;
}
private:
float length;
};
class Circle:public Shape
{
public:
Circle(float r):radius(r){};
void ShapeName()
{
cout<<"Square:"<<endl;
}
float area()
{
float s = PAI*radius*radius;
return s;
}
private:
float radius;
};
int main()
{
Shape *pt;
pt = new Triangle(3,4,5);
pt->ShapeName();
cout<<"Area:"<<pt->area()<<endl;
cout<<"================================"<<endl;
pt = new Square(2.5);
pt->ShapeName();
cout<<"Area:"<<pt->area()<<endl;
cout<<"================================"<<endl;
pt = new Circle(2.5);
pt->ShapeName();
cout<<"Area:"<<pt->area()<<endl;
return 0;
}
结果输出:
Triangle:
Area:6
================================
Square:
Area:6.25
================================
Square:
Area:19.6344
最新文章
- Spring 000 框架简介 (转载)
- js数组去重的hash方法
- Unity3d之个性化皮肤
- js 中 == 和=== 有什么区别?
- Python使用split使用多个字符分隔字符串
- 利用ksoap调用webservice
- AngularJS初始化闪烁
- 【HDOJ】4513 吉哥系列故事——完美队形II
- HDOJ 1032(POJ 1207) The 3n + 1 problem
- Notepad++在编程使用时的小技巧
- 【NO.3】 c program to caculate and display sum of two matrix
- hibernate它 10.many2many单向
- EasyuiAPI:菜单
- 《实战Nginx》读书笔记
- 04 Spinner 列表选中
- openlayer3相关扩展
- bzoj2982: combination(lucas定理板子)
- Spock - Document -04- Interaction Based Testing
- Django学习手册 - ORM数据类型
- css及HTML知识点