【题目】设计三角形类,通过增加构造函数,使对象在定义时能够进行初始化
特别要求:为全面体会构造函数的各种写法,本任务要求提交多个版本的程序,体现出你已经掌握下列知识点:(1)使用带参数构造函数,即Triangle(float x, float y, float z),三边长在调用时由实参直接给出;(2)设计默认构造函数,即不指定参数时,默认各边长为1;(3)使用默认参数的构造函数,不给定实参时,默认边长为1;(4)在构造函数中使用参数初始化表对数据成员初始化。
- #include<iostream>
- using namespace std;
- class Triangle
- {
- public:
- float perimeter(void);//计算三角形的周长
- float area(void);//计算并返回三角形的面积
- void showMessage();
- private:
- float a,b,c; //三边为私有成员数据
- };
- Void Triangle:: showMessage()
- {
- cout<<”三角形的三边长分别为:”<<a<<'\t'<<<<b<<<<'\t'<<<<c<<endl;
- cout<<"该三角形的周长为:"<< Tri1.Perimeter()<<'\t'<<"面积为:"<< Tri1.Area()<<endl<<endl;
- }
- void main(void)
- {
- Triangle Tri1;
- Tri1.showMessage();
- Triangle Tri2(7,8,9);
- Tri1.showMessage();
- }
- 解答一:
-
- #include<iostream>
- #include<Cmath>
- using namespace std;
- class Triangle
- {
- public:
- Triangle(){a=1;b=1;c=1;} //()设计默认构造函数,即不指定参数时,默认各边长为;
- Triangle(float x, float y, float z) {a=x; b=y; c=z;} //使用带参数构造函数,即Triangle(floatx, float y, float z),三边长在调用时由实参直接给出
- float perimeter(void);//计算三角形的周长
- float area(void);//计算并返回三角形的面积
- void showMessage();
- private:
- float a,b,c;//三边为私有成员数据
- };
- float Triangle::perimeter(void)
- {
- return (a +b + c);
- }
- float Triangle::area(void)
- {
- float 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;
- }
- void main(void)
- {
- Triangle Tri1; //定义三角形类的一个实例(对象)
- Tri1.showMessage();
- Triangle Tri2(7,8,9); //定义三角形类的一个实例(对象)
- Tri2.showMessage();
- system("pause");
- }
- 解答二:
-
- class Triangle
- {
- public:
- Triangle(float x=1, float y=1, float z=1);//3)使用默认参数的构造函数,不给定实参时,默认边长为;
- float perimeter(void);//计算三角形的周长
- float area(void);//计算并返回三角形的面积
- void showMessage();
- private:
- float a,b,c;//三边为私有成员数据
- };
- Triangle::Triangle(float x, float y, float z)
- {
- a=x;
- b=y;
- c=z;
- }
- 解答三:
-
- class Triangle
- {
- public:
- Triangle(floatx=1, float y=1, float z=1);
- float perimeter(void);//计算三角形的周长
- float area(void);//计算并返回三角形的面积
- void showMessage();
- private:
- float a,b,c;//三边为私有成员数据
- };
- Triangle::Triangle(float x, float y, float z):a(x),b(y),c(z){} //(4)在构造函数中使用参数初始化表对数据成员初始化。
-
- class Triangle
- {
- public:
- Triangle(float x=1, float y=1, float z=1) :a(x),b(y),c(z){}//内置的构造函数
- float perimeter(void);//计算三角形的周长
- float area(void);//计算并返回三角形的面积
- void showMessage();
- private:
- float a,b,c; //三边为私有成员数据
- };
感想:更加深层次的了解了构造函数的几种使用方法。