天天看點

第四周項目一——三角形類的構造函數(2)

/*
 *Copyright  (c)  2014,煙台大學計算機學院 
 *All rights reserved. 
 *檔案名稱: test.cpp
 *作        者:陳丹 
 *完成日期:2015年3月31日 
 *版本号:v1.0 
 *
 *問題描述:設計預設構造函數,即不指定參數時,預設各邊長為1。
 *輸入描述: 
 *程式輸出:
 */
#include<iostream>
#include<cmath>
using namespace std;
class Triangle
{
public:
    Triangle()
    {
        a=1;
        b=1;
        c=1;
    }
    double perimeter();//計算三角形的周長
    double area();//計算并傳回三角形的面積
    void showMessage();
private:
    double a,b,c; //三邊為私有成員資料
};
int main()
{
    Triangle Tri;   //調用預設構造函數,不指定參數時,預設各邊長為1;
    Tri.showMessage();
    return 0;
}
double Triangle::perimeter()
{
    return (a + b + c);
}

double Triangle::area()
{
    double s = (a + b + c) / 2;
    return sqrt(s * (s - a) * (s - b) * (s - c));
}
void Triangle::showMessage()
{
    cout<<"三角形的三邊長分别為:"<<a<<' '<<b<<' '<<c<<endl;
    cout<<"該三角形的周長為"<<perimeter()<<",面積為:"<<area()<<endl<<endl;
}
           

運作結果:

第四周項目一——三角形類的構造函數(2)