#include <iostream> #include <cmath> using namespace std; class Triangle { public: Triangle(double=1,double=1,double=1); double perimeter(); double area(); void show_message(); bool is_triangle(double,double,double); private: double a,b,c; }; int main() { Triangle tri1(3,4,5),tri2,tri3(1.5),tri4(1.5,3.7); tri1.show_message(); tri2.show_message(); tri3.show_message(); tri4.show_message(); return 0; } Triangle::Triangle(double x,double y,double z):a(x),b(y),c(z){} void Triangle::show_message() { if(is_triangle(a,b,c)) { cout<<"该三角形的三边长为:"<<a<<' '<<b<<' '<<c<<endl; cout<<"该三角形周长为:"<<perimeter()<<",面积为:"<<area()<<endl; } else { cout<<"该三角形三边长为:"<<a<<' '<<b<<' '<<c<<endl; cout<<"该三边无法构成三角形。"; } } 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)); } bool Triangle::is_triangle(double x,double y,double z) { if(x+y>z&&x+z>y&&y+z>x) return true; else return false; }
包含了各种初始化方式,不用担心关于初始化的一些重载的问题或者是函数冲突的问题。