问题及代码:
/*
*Copyright(c) 2016.烟台大学计算机与控制工程学院
*ALL rights reserved.
*文件名称:main.cpp
*作者:郝昱猛
*完成日期:2016年4月4日。
*问题描述:使用有默认参数的构造函数,不给定实参时,默认边长为1。
*/
#include <iostream>
#include <cmath>
using namespace std;
class Triangle
{
public:
Triangle(double x=1.0, double y=1.0, double z=1.0): 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();//三角形信息
bool isTriangle()
{
if(a+b > c && a+c > b && b+c > a)
return true;
else
return false;
}
private:
double a,b,c;
};
void Triangle::showMessage()
{
if(isTriangle())
{
cout << "三条边为:" <<a<< "," <<b<< "," <<c<< endl;
cout << "三角形的周长为:" <<perimeter() << "\t" << "面积为:" <<area() << endl;
}
else
cout<<"不能构成三角形"<<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 tri1;
tri1.showMessage();
Triangle tri2(1.5);
tri2.showMessage();
Triangle tri3(1.5,1.5);
tri3.showMessage();
Triangle tri4(7,8,9);
tri4.showMessage();
return 0;
}
运行结果: