摘要:本文主要向大家介绍了C/C++知识点之C++学习体会--构造函数初始化数据成员值的两条路,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了C/C++知识点之C++学习体会--构造函数初始化数据成员值的两条路,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
C++学习体会--构造函数初始化数据成员值的两条路
在编写一个应用时,我们会希望他们的变量,可以是指定的初始值。另外,在我需要的时候,当我定义相同的类但是不同的对象时,我可以设置其他的初始值。
#include
using namespace std;
class CBox
{
public:
double m_Length{ 1.0 };
double m_Width{ 1.0 };
double m_Height{ 1.0 };
CBox(double lv, double wv, double hv)//初始化路1:有实参赋予
{
cout << "Constrcurtor called." << endl;
m_Height = hv;
m_Length = lv;
m_Width = wv;
}
CBox() = default; //初始化路2:无实参,也可以是CBox(){};
double volume()//计算体积
{
return m_Length*m_Height*m_Width;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CBox box1{ 10.0, 10.0, 10.0 };//有实参
CBox box2;//默认初始化
cout << "Volume of box1=" << box1.volume() << endl;
cout << "Volume of box2=" << box2.volume() << endl;
return 0;
}
结果:
分析:
当类实体化的时候,默认进入与其相同名字的构造函数,当实体化对象时,如果存在实参,则将初始值一一对应lv,wv,hv赋值;如果没有实参,则使用没有函数体的默认构造函数,初始值为1.0;
优化代码:
#include
using namespace std;
class CBox
{
public:
double m_Length;
double m_Width;
double m_Height;
CBox(double lv=1.0, double wv=1.0, double hv=1.0)// 将上面分开初始化的方式合并;
{
cout << "Constrcurtor called." << endl;
m_Height = hv;
m_Length = lv;
m_Width = wv;
}
double volume()
{
return m_Length*m_Height*m_Width;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CBox box1{ 10.0, 10.0, 10.0 };
CBox box2;
cout << "Volume of box1=" << box1.volume() << endl;
cout << "Volume of box2=" << box2.volume() << endl;
return 0;
}
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号