*All rightreserved.
*文件名称:test.cpp
*作 者:张明宇
*完成日期:2016年3月27日
*/
问题及代码
设计三角形类带参数的构造函数,即Triangle(double x,double y,double z),三边长在调用时由实参直接给出,是对象在定义时能够进行初始化。需要的测试函数是:
int main()
{
Triangle Tri(7,8,9);//定义三角形类的一个实例(对象)
Tri.showMessage();//定义一个能显示三角形信息的成员函数
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
class Triangle
{
public:
Triangle(double x, double y, double z): a(x),b(y),c(z) {}//构造函数
void setABC(double x, double y, double z);
double perimeter();//计算三角形周长
double area();//计算三角形面积
void setA(double x) {a = x;}
void setB(double y) {b = y;}
void setC(double z) {c = z;}
double getA() {return a;}
double getB() {return b;}
double getC() {return c;}
void showMessage();//三角形信息
private:
double a,b,c;
};
void Triangle::showMessage()
{
cout << "三条边为:" <<a<< "," <<b<< "," <<c<< endl;
cout << "三角形的周长为:" <<perimeter() << "\t" << "面积为:" <<area() << endl;
}
void Triangle::setABC(double x, double y, double z)
{
a = x;
b = y;
c = z;
}
double Triangle::perimeter()
{
return a+b+c;
}
double Triangle::area()
{
double p = (a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c));
};
int main()
{
Triangle tri(7,8,9);
tri.showMessage();
return 0;
}