
/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称: class Triangle
* 作 者: 刘程程
* 完成日期: 2012 年 03 月 19 日
* 版 本 号: 1.0
* 对任务及求解方法的描述部分
* 输入描述:三角形的三边
* 问题描述: 计算周长和面积
* 程序输出: 三角形的周长和面积
* 程序头部的注释结束
*/
(1)使用带参数构造函数,即Triangle(float x, float y, float z),三边长在调用时由实参直接给出;
#include<iostream>
#include<cmath>
using namespace std;
class Triangle
{public:
Triangle(float, float, float);
float perimeter(void);//计算三角形的周长
float area(void);//计算并返回三角形的面积
void showMessage();
private:
float a,b,c; //三边为私有成员数据
};
Triangle :: Triangle(float x, float y, float z)
{
a = x;
b = y;
c = z;
}
float Triangle :: perimeter(void)
{
float t;
t = a + b + c;
return t;
}
float Triangle :: area(void)
{
float s, f;
s = (a + b + c)/2;
f = sqrt(s * (s - a)*(s - b)*(s - c) );
return f;
}
void Triangle:: showMessage()
{
cout<<"三角形的三边长分别为:"<<a<<" "<<b<<" "<<c<<endl;
cout<<"该三角形的周长为:"<< perimeter()<<'\t'<<"面积为:"<< area()<<endl;
}
void main(void)
{
Triangle Tri2(7,8,9); //定义三角形类的一个实例(对象)
Tri2.showMessage();
}
感悟:通过反复的改错,我更加深刻了解了类及对象。