1.2.4 对象成员的初始化
在上述程序中,所定义的类基本上都是一个。但在实际应用中往往需要多个类,这时就可能把一个已定义类的对象作为另一个类的成员。为了能对这些对象成员进行初始化,C++(www.cppentry.com)允许采用下面这样的构造函数定义格式:
- 类名::构造函数名(形参表) : 对象l(参数表), 对象2(参数表), ... , 对象n(参数表)
- {...}
【例1.2】对象成员的初始化(Ex1_02):
- #include <iostream.h>
- class CPoint
- {
- public:
- CPoint(int x, int y) {
- nPosX = x; nPosY = y;
- cout<<"CPoint类构造函数"<<endl;
- }
- void ShowPos() {
- cout<<"当前位置:x = "<<nPosX<<", y = "<<nPosY<<endl;
- }
- private:
- int nPosX, nPosY;
- };
-
- class CSize
- {
- public:
- CSize(int l, int w) {
- nLength = l; nWidth = w;
- cout<<"CSize类构造函数"<<endl;
- }
- void ShowSize() {
- cout<<"当前大小:l = "<<nLength<<", w = "<<nWidth<<endl;
- }
- private:
- int nLength, nWidth;
- };
-
- class CRect
- {
- public:
- CRect(int left, int top, int right, int bottom);
- void Show() {
- ptCenter.ShowPos();
- size.ShowSize();
- }
- private:
- CPoint ptCenter;
- CSize size;
- };
-
- CRect::CRect(int left, int top, int right, int bottom)
- :size(right-left, bottom-top), ptCenter((left+right)/2, (top+bottom)/2)
- { }
-
- void main()
- {
- CRect rc(10, 120, 70, 230);
- rc.Show();
- }
运行结果为:
- CPoint类构造函数
- CSize类构造函数
- 当前位置:x = 40, y = 175
- 当前大小:l = 60, w = 110
代码中,CRect类的私有成员CPoint类对象ptCenter和CSize类对象size的初始化是在CRect类构造函数实现时进行的。在此需要做出如下一些说明。
(1) 类的成员对象必须初始化,但不能将成员对象直接在构造函数体内进行初始化,如下面的初始化是不可以的:
- CRect(int left, int top, int right, int bottom)
- {
- ptCenter = CPoint((left+right)/2, (top + bottom)/2);
- size = CSize(right-left, bottom-top);
- }
(2) 对象成员初始化时,必须有相应的构造函数,且多个对象成员的构造次序不是按初始化成员列表的顺序,而是按各类声明的先后次序进行的,从例子的运行结果可以得到证明。
(3) 成员对象初始化可在类构造函数定义时进行,例如:
- CRect::CRect(int left, int top, int right, int bottom)
- :size(right-left, bottom-top), ptCenter((left+right)/2, (top+bottom)/2)
- {
- }
【责任编辑:
云霞 TEL:(010)68476606】