标签:
<span style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15.5555562973022px; line-height: 35px;">【项目1-三角形类的构造函数】</span><br style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15.5555562973022px; line-height: 35px;" /><span style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15.5555562973022px; line-height: 35px;"> 设计三角形类,通过增加构造函数,使对象在定义时能够进行初始化,可以由下面的类声明开始,需要自己实现相关的成员函数,以及增加要求的构造函数</span>
<span style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15.5555562973022px; line-height: 35px;"><span style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15.5555562973022px; line-height: 35px;">(1)使用带参数构造函数,即Triangle(double x, double y, double z),三边长在调用时由实参直接给出。需要的测试函数是:</span> </span>
<span style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15.5555562973022px; line-height: 35px;"><span style="color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15.5555562973022px; line-height: 35px;"></span></span><pre name="code" class="cpp">int main(){
Triangle Tri(7,8,9); //定义三角形类的一个实例(对象)
Tri.showMessage();
return 0;
}
#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 Tri(7,8,9);
Tri.showMessage();
return 0;
}
运行结果:
标签:
原文地址:http://blog.csdn.net/zs9528/article/details/44812001