頭文件: [cpp] [cpp] class Triangle{ private: double a,b,c; public: inline void setA(double x){a=x;} inline void setB(double y){b=y;} inline void setC(double z){c=z;} inline double getA(){return a;} inline double getB(){return b;} inline double getC(){return c;} bool isTriangle(); double perimeter(void); double area(void); }; 類定義文件: [cpp] #include "triangle.h" #include<Cmath> using namespace std; double Triangle::perimeter(void)//計算三角形的周長 { return a+b+c; } double Triangle::area(void)//計算並返回三角形的面積 { double s=(a+b+c)/2; return sqrt(s*(s-a)*(s-b)*(s-c)); } bool Triangle::isTriangle() { if((a+b)>c&&(a-b)<c) return true; else return false; } 主文件: [cpp] #include<iostream> #include "triangle.h" using namespace std; int main(){ Triangle tril;//定義三角形的一個實例(類) double x,y,z; cout<<"請輸入三角形的三邊;"; cin>>x>>y>>z; tril.setA(x); tril.setB(y); tril.setC(z); if(tril.isTriangle()){ cout<<"三條邊為:"<<tril.getA()<<','<<tril.getB()<<','<<tril.getC()<<endl; cout<<"三角形的周長為:"<<tril.perimeter()<<'\t'<<"面積為:"<<tril.area()<<endl; } else cout<<"不能構成三角形!"<<endl; system("pause"); return 0; } 運行結果: