8.9.3 实现CBox类(1)
我们实际上需要考虑希望嵌入CBox类内部的错误防护程度。为说明类的各个方面而定义的基本的CBox类可以作为一个始点,但还应该更深入地考虑其他几点。构造函数不够完善,因为不能确保CBox对象的尺寸有效,因此可能首先应该确保始终获得有效的对象。为此,可以重新定义基本的CBox类:
- class CBox // Class definition at global scope
- {
- public:
- // Constructor definition
- explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0): m_Height(hv)
- {
- if(lv < 0.0 || wv < 0.0 || hv < 0.0)
- throw "Negative dimension specified for CBox object.";
- m_Length = std::max(lv, wv);
- m_Width = std::min(lv, wv);
- // Length is now greater than or equal to width
- if(m_Height > m_Length)
- {
- m_Height = m_Length;
- m_Length = hv;
- // m_Height is still greater than m_Width so swap them
- double temp = m_Width;
- m_Width = m_Height;
- m_Height = temp;
- }
- else if( m_Height > m_Width)
- {
- m_Height = m_Width;
- m_Width = hv;
- }
- }
- // Function to calculate the volume of a box
- double Volume() const
- {
- return m_Length*m_Width*m_Height;
- }
- // Function providing the length of a box
- double GetLength() const { return m_Length; }
- // Function providing the width of a box
- double GetWidth() const { return m_Width; }
- // Function providing the height of a box
- double GetHeight() const { return m_Height; }
- private:
- double m_Length; // Length of a box in inches
- double m_Width; // Width of a box in inches
- double m_Height; // Height of a box in inches
- };
构造函数现在是可靠的,因为在构造函数中将任何被用户设置成小于0的尺寸都会抛出一个异常。
该类的默认复制构造函数和默认赋值运算符是令人满意的,因为我们不需要给数据成员动态分配内存。在该情况下,默认析构函数同样工作得很好,因此不需要定义它。现在,应该考虑要支持类对象的比较功能都需要做些什么。
1. 比较CBox对象
我们应该包括对>、>=、==、<和<=运算符的支持,使它们能够处理两个操作数都是CBox对象的情况,还能处理一个操作数是CBox对象、另一个操作数是double类型数值的情况。这样总共有18个运算符函数。一旦定义了<和==运算符函数,就可以从utility头文件的模板中得到4个带双操作数的运算符函数,这些都在Ex8_06中完成了:
- // Operator function for < comparing CBox objects
- bool operator<(const CBox& aBox) const
- { return this->Volume() < aBox.Volume(); }
- // Operator function for == comparing CBox objects
- bool operator==(const CBox& aBox) const
- { return this->Volume() == aBox.Volume(); }
比较左操作数是CBox对象、右操作数是一个常量的所有4个运算符函数可以放在类中:
- // Function for testing if a CBox object is > a value
- bool operator>(const double& value) const
- { return Volume() > value; }
- // Function for testing if a CBox object is < a value
- bool operator<(const double& value) const
- { return Volume() < value; }
- // Function for testing if a CBox object is >= a value
- bool operator>=(const double& value) const
- { return Volume() >= value; }
- // Function for testing if a CBox object is <= a value
- bool operator<=(const double& value) const
- { return Volume() <= value; }
- // Function for testing if a CBox object is == a value
- bool operator==(const double& value) const
- { return Volume() == value; }
- // Function for testing if a CBox object is != a value
- bool operator!=(const double& value) const
- { return Volume() != value; }