设为首页 加入收藏

TOP

8.6.3 实现CBox类(6)
2013-10-07 12:35:09 来源: 作者: 【 】 浏览:67
Tags:8.6.3 实现 CBox

8.6.3  实现CBox类(6)

包含内联函数定义的公有部分已经添加到类定义之中。我们需要修改各个定义以提供正确的返回值,还需要将这些函数声明为const。例如,GetHeight()函数的代码应该被修改成如下形式:

  1. double GetHeight(void) const  
  2. {  
  3. return m_Height;  

我们应该以类似的方式修改GetWidth()和GetLength()函数的定义。Volume()函数定义应该被修改成:

  1. double Volume(void) const  
  2. {  
  3. return m_Length*m_Width*m_Height;  

我们可以直接在显示代码的编辑器窗格中输入其他非内联的成员函数,当然也可以使用Add Member Function Wizard来做这件事, 如此实践一番将对我们有益。像以前一样,在Class View选项卡上右击CBox,并从上下文菜单中选择Add/Add Function…菜单项。如图8-12所示,之后我们就可以在显示出来的对话框中输入希望添加的第一个函数的详细数据。

 
(点击查看大图)图  8-12
图中将operator+()函数定义成返回类型为CBox的公有函数。形参的类型和名称也已经被输入到适当的字段中。在单击Finish按钮之前,我们必须单击Add按钮使该形参显示在形参列表中,这样还将更新Add Member Function Wizard对话框底部显示的函数签名。之后,我们可以输入另一个形参的详细数据-- 如果有的话,并再次单击Add按钮添加该形参。图中的对话框还输入了一行注释,该向导将把注释插入到Box.h和Box.cpp文件中。当我们单击Finish按钮时,该函数的声明将添加到Box.h文件的类定义中,其骨架定义将添加到Box.cpp文件中。operator+()函数需要被声明为const,因此我们必须将const关键字添加到类定义内该函数的声明以及Box.cpp文件内该函数的定义中,还必须添加如下所示的函数体代码:
  1. CBox CBox::operator +(const CBox& aBox) const  
  2. {  
  3. // New object has larger length and width of the two,  
  4. // and sum of the two heights  
  5. return CBox(m_Length > aBox.m_Length   m_Length : aBox.m_Length,  
  6. m_Width > aBox.m_Width   m_Width : aBox.m_Width,  
  7. m_Height + aBox.m_Height);  

我们需要为前面介绍的operator*()函数和operator/()函数重复上述过程。当完成这些工作以后,Box.h文件中的类定义应该如下所示:

  1. #pragma once  
  2.  
  3. class CBox  
  4. {  
  5. public:  
  6. CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0);  
  7. ~CBox(void);  
  8.  
  9. private:  
  10. // Length of a box in inches  
  11. double m_Length;  
  12.  
  13. // Width of a box in inches  
  14. double m_Width;  
  15.  
  16. // Height of a box in inches  
  17. double m_Height;  
  18. public:  
  19.  
  20. double GetHeight(void) const  
  21. {  
  22. return m_Height;  
  23. }  
  24. public:  
  25.  
  26. double GetWidth(void) const  
  27. {  
  28. return m_Width;  
  29. }  
  30. public:  
  31.  
  32. double GetLength(void) const  
  33. {  
  34. return m_Length;  
  35. }  
  36. public:  
  37.  
  38. double Volume(void) const  
  39. {  
  40. return m_Length*m_Width*m_Height;  
  41. }  
  42. public:  
  43.  
  44. // Overloaded addition operator  
  45. CBox operator+(const CBox& aBox) const;  
  46. public  
  47.  
  48. // Multiply a box by an integer  
  49. CBox operator*(int n) const;  
  50. public:  
  51.  
  52. // Divide one box into another  
  53. int operator/(const CBox& aBox) const;  
  54. }; 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇9.4 派生类中的复制构造函数(2) 下一篇8.6.3 实现CBox类(5)

评论

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