C++学习-构造函数初始化列表(4)(二)

2014-11-24 12:17:27 · 作者: · 浏览: 3

CInit(const CObj & obj) : mObj(obj)
{
}执行结果为:
[plain] 调用默认构造函数

调用复制构造函数
调用默认构造函数

调用复制构造函数在构造函数CInit的初始化列表初始化mObj对象时,调用了复制构造函数1次,总共需要1个行为。

2.若CInit的构造函数为:

[cpp] CInit(const CObj & obj)
{
mObj = obj;
}
CInit(const CObj & obj)
{
mObj = obj;
}执行结果为:


[plain] 调用默认构造函数

调用默认构造函数
数据赋值
调用默认构造函数

调用默认构造函数
数据赋值

在构造函数体中赋值mObj对象时,首先调用默认构造函数,其次是调用operator=赋值运算符,总共需要2个行为。

所以可以得出这么一个结论:对于用户自定义的类类型,使用构造函数初始化列表进行初始化的效率,比在构造函数体中赋值初始化的效率更高。对于内置类型,效率是差不多的。

五.构造函数初始化列表的使用例子

[cpp] /*类成员的初始化: 求2点组成的矩形*/
#include

using namespace std;

class CCenterPoint
{
public:
CCenterPoint(int posX, int posY) : mPosX(posX), mPosY(posY)
{
}
void ShowPos() const
{
cout << "2点之间的中点坐标: (" << mPosX << "," << mPosY << ")" << endl;
}
private:
int mPosX;
int mPosY;
};

class CArea
{
public:
CArea(int length, int width) : mLength(length), mWidth(width)
{
}
void ShowArea() const
{
cout << "2点组成的矩形面积: " << mLength * mWidth << endl;
}
private:
int mLength;
int mWidth;
};

class CRect
{
public:
CRect(int posX1, int posY1, int posX2, int posY2)
: mPoint((posX1+posY1)/2, (posX2+posY2)/2),
mArea(posX2-posX1, posY2-posY1)
{
}
void Show() const
{
mPoint.ShowPos();
mArea.ShowArea();
}
private:
CCenterPoint mPoint;
CArea mArea;
};

int main()
{
CRect rect(10, 100, 20, 200);
rect.Show();

return 0;
}
/*类成员的初始化: 求2点组成的矩形*/
#include

using namespace std;

class CCenterPoint
{
public:
CCenterPoint(int posX, int posY) : mPosX(posX), mPosY(posY)
{
}
void ShowPos() const
{
cout << "2点之间的中点坐标: (" << mPosX << "," << mPosY << ")" << endl;
}
private:
int mPosX;
int mPosY;
};

class CArea
{
public:
CArea(int length, int width) : mLength(length), mWidth(width)
{
}
void ShowArea() const
{
cout << "2点组成的矩形面积: " << mLength * mWidth << endl;
}
private:
int mLength;
int mWidth;
};

class CRect
{
public:
CRect(int posX1, int posY1, int posX2, int posY2)
: mPoint((posX1+posY1)/2, (posX2+posY2)/2),
mArea(posX2-posX1, posY2-posY1)
{
}
void Show() const
{
mPoint.ShowPos();
mArea.ShowArea();
}
private:
CCenterPoint mPoint;
CArea mArea;
};

int main()
{
CRect rect(10, 100, 20, 200);
rect.Show();

return 0;
}执行结果:


[plain] 2点之间的中点坐标: (55,110)
2点组成的矩形面积: 1000
2点之间的中点坐标: (55,110)
2点组成的矩形面积: 1000
Happy Learning!

摘自 gzshun的专栏