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 |
图中将operator+()函数定义成返回类型为CBox的公有函数。形参的类型和名称也已经被输入到适当的字段中。在单击Finish按钮之前,我们必须单击Add按钮使该形参显示在形参列表中,这样还将更新Add Member Function Wizard对话框底部显示的函数签名。之后,我们可以输入另一个形参的详细数据-- 如果有的话,并再次单击Add按钮添加该形参。图中的对话框还输入了一行注释,该向导将把注释插入到Box.h和Box.cpp文件中。当我们单击Finish按钮时,该函数的声明将添加到Box.h文件的类定义中,其骨架定义将添加到Box.cpp文件中。operator+()函数需要被声明为const,因此我们必须将const关键字添加到类定义内该函数的声明以及Box.cpp文件内该函数的定义中,还必须添加如下所示的函数体代码:
- 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;
- };