码迷,mamicode.com
首页 > 其他好文 > 详细

在构造函数中使用初始化表

时间:2014-05-21 07:22:03      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   c   code   http   

刚接触初始化表的时候有点茫然,慢慢的我也熟悉了,初始化表,初始化表可以减少代码量提高编程效率

抛砖引玉:先从一个例子说明初始化表的作用,

定义一个对象数组并且使用构造函数对其初始化

#include <iostream>

using namespace std;

class Box//Box类
{
public:

	//构造函数
	Box(int h, int w, int l);

	int volume();//计算Box的面积

private:
	int height;
	int width;
	int length;
};

//构造函数
Box::Box(int h, int w, int l)
{
	height = h;
	width = w;
	length = l;
}

//计算体积
int Box::volume()
{
	int v;
	v = height * width * length;

	return v;
}

void main()
{
	Box a[3] = {
		Box(15,18,20),
		Box(10,12,15),
		Box(16,20,26)
	};

	cout<<"volume of a[0] is "<<a[0].volume()<<endl;
	cout<<"volume of a[1] is "<<a[1].volume()<<endl;
	cout<<"volume of a[2] is "<<a[2].volume()<<endl;

	system("pause");
}

执行结果:

bubuko.com,布布扣


将构造函数改成初始化表的形式后的代码:

#include <iostream>

using namespace std;

class Box//Box类
{
public:

	//以初始化表的形式表示构造函数
	Box(int h, int w, int l):height(h),width(w),length(l){}

	int volume();//计算Box的面积

private:
	int height;
	int width;
	int length;
};

//计算体积
int Box::volume()
{
	int v;
	v = height * width * length;

	return v;
}

void main()
{
	Box a[3] = {
		Box(15,18,20),
		Box(10,12,15),
		Box(16,20,26)
	};

	cout<<"volume of a[0] is "<<a[0].volume()<<endl;
	cout<<"volume of a[1] is "<<a[1].volume()<<endl;
	cout<<"volume of a[2] is "<<a[2].volume()<<endl;

	system("pause");
}

执行结果:

bubuko.com,布布扣


通过上面两段代码的比较发现两段代码的执行结果一样,而两段代码的不同点就是第一段代码使用的是普通的构造函数,而第二段代码在构造函数中使用了初始化表的形式

第一段使用普通的构造函数的代码:

Box::Box(int h, int w, int l)
{
	height = h;
	width = w;
	length = l;
}


使用初始化表的形式的代码:

	//以初始化表的形式表示构造函数
	Box(int h, int w, int l):height(h),width(w),length(l){}

通过比较发现使用初始化表的形式和使用普通的构造函数的形式可以实现相同的功能,而使用初始化表的代码量比普通构造函数的代码量少只有一行,所以推荐在构造函数中使用初始化表

在构造函数中使用初始化表,布布扣,bubuko.com

在构造函数中使用初始化表

标签:style   blog   class   c   code   http   

原文地址:http://blog.csdn.net/u010105970/article/details/26387843

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!