8.9.3 实现CBox类(7)
可以用相同的方式把前面实现的operator==()和Volume()成员添加到类定义中:
- // Operator function for == comparing CBox objects
- bool CBox::operator==(const CBox& aBox) const
- {
- return Volume() == aBox.Volume();
- }
- // Calculate the box volume
- double CBox::Volume(void) const
- {
- return m_Length*m_Width*m_Height;
- }
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关键字,还必须添加如下所示的函数代码体:
- CBox CBox::operator +(const CBox& aBox) const
- {
- // New object has larger length and width of the two,
- // and sum of the two heights
- return CBox(m_Length > aBox.m_Length m_Length : aBox.m_Length,
- m_Width > aBox.m_Width m_Width : aBox.m_Width,
- m_Height + aBox.m_Height);
- }
当为前面介绍的operator*()函数和operator/()函数重复上述过程,之后Box.h文件中的类定义应该如下所示:
- #pragma once
- #include <utility>
- using namespace std::rel_ops;
- class CBox
- {
- public:
- explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0);
- ~CBox(void);
- private:
- double m_Length;
- double m_Width;
- double m_Height;
- public:
- bool operator<(const CBox& aBox) const;
- bool operator==(const CBox& aBox) const;
- double Volume(void) const;
- double GetLength() const { return m_Length; }
- double GetWidth() const { return m_Width; }
- double GetHeight() const { return m_Height; }
- CBox operator+(const CBox& aBox) const; // Addition operator for CBox objects
- CBox operator*(int n) const; // Multiply operator for CBox objects
- int operator/(const CBox& aBox) const; // Division operator for CBox objects
- };