8.6.3 实现CBox类(6)
包含内联函数定义的公有部分已经添加到类定义之中。我们需要修改各个定义以提供正确的返回值,还需要将这些函数声明为const。例如,GetHeight()函数的代码应该被修改成如下形式:
- double GetHeight(void) const
- {
- return m_Height;
- }
我们应该以类似的方式修改GetWidth()和GetLength()函数的定义。Volume()函数定义应该被修改成:
- double Volume(void) const
- {
- return m_Length*m_Width*m_Height;
- }
我们可以直接在显示代码的编辑器窗格中输入其他非内联的成员函数,当然也可以使用Add Member Function Wizard来做这件事, 如此实践一番将对我们有益。像以前一样,在Class View选项卡上右击CBox,并从上下文菜单中选择Add/Add Function…菜单项。如图8-12所示,之后我们就可以在显示出来的对话框中输入希望添加的第一个函数的详细数据。
|
| (点击查看大图)图 8-12 |
- 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
- class CBox
- {
- public:
- CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0);
- ~CBox(void);
- private:
- // Length of a box in inches
- double m_Length;
- // Width of a box in inches
- double m_Width;
- // Height of a box in inches
- double m_Height;
- public:
- double GetHeight(void) const
- {
- return m_Height;
- }
- public:
- double GetWidth(void) const
- {
- return m_Width;
- }
- public:
- double GetLength(void) const
- {
- return m_Length;
- }
- public:
- double Volume(void) const
- {
- return m_Length*m_Width*m_Height;
- }
- public:
- // Overloaded addition operator
- CBox operator+(const CBox& aBox) const;
- public
- // Multiply a box by an integer
- CBox operator*(int n) const;
- public:
- // Divide one box into another
- int operator/(const CBox& aBox) const;
- };
