设为首页 加入收藏

TOP

9.4 派生类中的复制构造函数(1)
2013-10-07 12:40:19 来源: 作者: 【 】 浏览:75
Tags:9.4 派生 复制 构造 函数

9.4  派生类中的复制构造函数(1)

记住,复制构造函数是在声明用同类对象初始化的对象时被自动调用的。看一看下面这两条语句:

  1. CBox myBox(2.0, 3.0, 4.0); // Calls constructor  
  2. CBox copyBox(myBox); // Calls copy constructor 

第一条语句调用接受3个double类型实参的构造函数,第二条语句调用复制构造函数。如果我们不提供自定义的复制构造函数,则编译器将提供一个默认的复制构造函数,将初始化对象的成员逐一复制到新对象的对应成员中。为了解执行过程中所发生的事情,我们可以给CBox类添加自定义的复制构造函数版本,然后以CBox类的定义为基础来使用CCandyBox类。

  1. // Box.h in Ex9_05  
  2. #pragma once  
  3. #include <iostream> 
  4. using std::cout;  
  5. using std::endl;  
  6.  
  7. class CBox      // Base class definition  
  8. {  
  9. public:  
  10. // Base class constructor  
  11. CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0):  
  12. m_Length(lv), m_Width(wv), m_Height(hv)  
  13. { cout << endl << "CBox constructor called"; }  
  14.  
  15. // Copy constructor  
  16. CBox(const CBox& initB)  
  17. {  
  18. cout << endl << "CBox copy constructor called";  
  19. m_Length = initB.m_Length;  
  20. m_Width = initB.m_Width;  
  21. m_Height = initB.m_Height;  
  22. }  
  23.  
  24. // CBox destructor - just to track calls  
  25. ~CBox()  
  26. { cout << "CBox destructor called" << endl; }  
  27.  
  28. protected:  
  29. double m_Length;  
  30. double m_Width;  
  31. double m_Height;  
  32. }; 

我们还记得,为了避免无穷无尽地调用自身,复制构造函数的形参必须被指定为引用,否则将需要复制以传值方式传递的实参。当该示例中的复制构造函数被调用时,将向屏幕上输出一条消息,因此我们从输出中可以看出事件发生的时间。

我们将使用Ex9_04.cpp文件中CCandyBox类的版本,这里再次将其写出:

  1. // CandyBox.h in Ex9_05  
  2. #pragma once  
  3. #include "Box.h"  
  4. #include <iostream> 
  5. using std::cout;  
  6. using std::endl;  
  7.  
  8. class CCandyBox: public CBox  
  9. {  
  10. public:  
  11. char* m_Contents;  
  12.  
  13. // Derived class function to calculate volume  
  14. double Volume() const  
  15. { return m_Length*m_Width*m_Height; }  
  16.  
  17. // Constructor to set dimensions and contents  
  18. // with explicit call of CBox constructor  
  19. CCandyBox(double lv, double wv, double hv, char* str = "Candy")  
  20.                             :CBox(lv, wv, hv) // Constructor  
  21. {  
  22. cout << endl <<"CCandyBox constructor2 called";  
  23. m_Contents = new char[ strlen(str) + 1 ];  
  24. strcpy_s(m_Contents, strlen(str) + 1, str);  
  25. }  
  26.  
  27. // Constructor to set contents  
  28. // calls default CBox constructor automatically  
  29. CCandyBox(char* str = "Candy")              // Constructor  
  30. {  
  31. cout << endl << "CCandyBox constructor1 called";  
  32. m_Contents = new char[ strlen(str) + 1 ];  
  33. strcpy_s(m_Contents, strlen(str) + 1, str);  
  34. }  
  35.  
  36. ~CCandyBox() // Destructor  
  37. {  
  38. cout << "CCandyBox destructor called" << endl;  
  39. delete[] m_Contents;  
  40. }  

这里还没有给CCandyBox类添加复制构造函数,因此我们将依赖编译器生成的版本。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇9.9.7 委托和事件(1) 下一篇9.5.2 对类友元关系的限制

评论

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