(4)在构造函数中使用参数初始化表对数据成员初始化,这是一种更加提倡的写法。测试函数同(1)。
#include <iostream>
#include <cmath>
using namespace std;
class Triangle
{
public:
double perimeter();
double area();
void showMessage();
Triangle(double x,double y,double z):a(x),b(y),c(z){};
private:
double a,b,c;
};
void Triangle::showMessage()
{
cout<<"三角形的三边长分别为:"<<a<<‘ ‘<<b<<‘ ‘<<c<<endl;
cout<<"该三角形的周长为"<<perimeter()<<",面积为:"<<area()<<endl<<endl;
}
double Triangle::perimeter()
{
return a+b+c;
}
double Triangle::area()
{
double p,s;
p=(a+b+c)/2;
s=sqrt(p*(p-a)*(p-b)*(p-c));
return s;
}
int main()
{
Triangle Tri1(1,1,1);
Tri1.showMessage();
Triangle Tri2(1.5,1,1);
Tri2.showMessage();
Triangle Tri3(1.5,1.5,1);
Tri3.showMessage();
Triangle Tri4(7,8,9);
Tri4.showMessage();
return 0;
}
运行结果:
时间: 2025-01-02 06:54:10