设为首页 加入收藏

TOP

1.2.4 对象成员的初始化
2013-10-07 01:08:10 来源: 作者: 【 】 浏览:69
Tags:1.2.4 对象 成员 初始

1.2.4  对象成员的初始化

在上述程序中,所定义的类基本上都是一个。但在实际应用中往往需要多个类,这时就可能把一个已定义类的对象作为另一个类的成员。为了能对这些对象成员进行初始化,C++(www.cppentry.com)允许采用下面这样的构造函数定义格式:

  1. 类名::构造函数名(形参表) : 对象l(参数表), 对象2(参数表), ... , 对象n(参数表)  
  2. {...} 

【例1.2】对象成员的初始化(Ex1_02):

  1. #include <iostream.h>  
  2. class CPoint  
  3. {  
  4. public:  
  5. CPoint(int x, int y) {   
  6. nPosX = x;  nPosY = y;  
  7. cout<<"CPoint类构造函数"<<endl; // endl作用相当于回车换行  
  8. }  
  9. void ShowPos() {   
  10. cout<<"当前位置:x = "<<nPosX<<", y = "<<nPosY<<endl;  
  11. }  
  12. private:  
  13. int nPosX, nPosY;  
  14. };  
  15.  
  16. class CSize  
  17. {  
  18. public:  
  19. CSize(int l, int w) {   
  20. nLength = l;  nWidth = w;   
  21. cout<<"CSize类构造函数"<<endl;  
  22. }  
  23. void ShowSize() {   
  24. cout<<"当前大小:l = "<<nLength<<", w = "<<nWidth<<endl;  
  25. }  
  26. private:  
  27. int nLength, nWidth;  
  28. };  
  29.  
  30. class CRect  
  31. {  
  32. public:  
  33. CRect(int left, int top, int right, int bottom);  
  34. void Show() {  
  35. ptCenter.ShowPos();  
  36. size.ShowSize();  
  37. }  
  38. private:  
  39. CPoint ptCenter;  
  40. CSize size;  
  41. };  
  42.  
  43. CRect::CRect(int left, int top, int right, int bottom)  
  44. :size(right-left, bottom-top), ptCenter((left+right)/2, (top+bottom)/2)  
  45. {  }  
  46.  
  47. void main()  
  48. {  
  49. CRect rc(10, 120, 70, 230);  
  50. rc.Show();  

运行结果为:

  1. CPoint类构造函数  
  2. CSize类构造函数  
  3. 当前位置:x = 40, y = 175  
  4. 当前大小:l = 60, w = 110 

代码中,CRect类的私有成员CPoint类对象ptCenter和CSize类对象size的初始化是在CRect类构造函数实现时进行的。在此需要做出如下一些说明。

(1) 类的成员对象必须初始化,但不能将成员对象直接在构造函数体内进行初始化,如下面的初始化是不可以的:

  1. CRect(int left,  int top,  int right, int bottom)  
  2. {   
  3. ptCenter = CPoint((left+right)/2, (top + bottom)/2);  
  4. size = CSize(right-left, bottom-top);  

(2) 对象成员初始化时,必须有相应的构造函数,且多个对象成员的构造次序不是按初始化成员列表的顺序,而是按各类声明的先后次序进行的,从例子的运行结果可以得到证明。

(3) 成员对象初始化可在类构造函数定义时进行,例如:

  1. CRect::CRect(int left, int top, int right, int bottom)  
  2. :size(right-left, bottom-top), ptCenter((left+right)/2, (top+bottom)/2)  
  3. {  

【责任编辑:云霞 TEL:(010)68476606】

回书目   上一节   下一节

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.4.3 纯虚函数与抽象类 下一篇1.2.7 友元函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: