设为首页 加入收藏

TOP

8.9.3 实现CBox类(7)
2013-10-07 16:10:11 来源: 作者: 【 】 浏览:84
Tags:8.9.3 实现 CBox

8.9.3  实现CBox类(7)

可以用相同的方式把前面实现的operator==()和Volume()成员添加到类定义中:
 

  1. // Operator function for == comparing CBox objects  
  2. bool CBox::operator==(const CBox& aBox) const  
  3. {  
  4. return Volume() == aBox.Volume();  
  5. }  
  6. // Calculate the box volume  
  7. double CBox::Volume(void) const  
  8. {  
  9. return m_Length*m_Width*m_Height;  
  10. }  

Utility头文件中的模板将处理!=、>、<=和>=运算符函数。稍后将介绍这些比较CBox对象和数值的运算符函数。

现在可以把前面的GetHeight()、GetWidth()和GetLength()函数添加为内联的类成员。这些内容将留给读者完成,可以使用Add | Add Function菜单选项或直接输入它们。

用于加法、乘法和除法操作的运算符函数可以使用Add Member Function Wizard输入为类成员,如此实践一番将对我们有益。像以前一样,在Class View选项卡上右击CBox,并从上下文菜单中选择Add | Add Function…菜单项。如图8-11所示,之后就可以在显示的对话框中输入operator+()函数的详细数据。
 

图8-11显示了单击Add按钮给列表添加形参后的对话框。当单击Finish按钮时,将在Box.h文件的类定义中添加该函数的声明,在Box.cpp文件中添加其框架定义。operator+()函数需要声明为const,因此必须在类定义内该函数的声明中以及Box.cpp文件内该函数的定义中添加const关键字,还必须添加如下所示的函数代码体:
 

  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);  
  8. }  

当为前面介绍的operator*()函数和operator/()函数重复上述过程,之后Box.h文件中的类定义应该如下所示:
 

  1. #pragma once  
  2. #include <utility> 
  3. using namespace std::rel_ops;  
  4. class CBox  
  5. {  
  6. public:  
  7. explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0);  
  8. ~CBox(void);  
  9. private:  
  10. double m_Length;  
  11. double m_Width;  
  12. double m_Height;  
  13. public:  
  14. bool operator<(const CBox& aBox) const;  
  15. bool operator==(const CBox& aBox) const;  
  16. double Volume(void) const;  
  17. double GetLength() const { return m_Length; }  
  18. double GetWidth() const { return m_Width; }  
  19. double GetHeight() const { return m_Height; }  
  20. CBox operator+(const CBox& aBox) const;         // Addition operator for CBox objects  
  21. CBox operator*(int n) const;                                                // Multiply operator for CBox objects  
  22. int operator/(const CBox& aBox) const;              // Division operator for CBox objects  
  23. };  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇8.9.3 实现CBox类(6) 下一篇8.9.3 实现CBox类(8)

评论

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

·python数据分析岗的 (2025-12-25 10:02:21)
·python做数据分析需 (2025-12-25 10:02:19)
·成为一个优秀的pytho (2025-12-25 10:02:16)
·Java后端面试实习自 (2025-12-25 09:24:21)
·Java LTS版本有哪些 (2025-12-25 09:24:18)