8.4.1 实现重载的运算符(2)
试一试:运算符重载
可以通过如下示例练习如何使用CBox对象的operator<()函数:
- // Ex8_03.cpp
- // Exercising the overloaded 'less than' operator and equality operators
- #include <iostream> // For stream I/O
- using std::cout;
- using std::endl;
- 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_Length(lv), m_Width(wv), m_Height(hv)
- {
- cout << endl << "Constructor called.";
- }
- // Function to calculate the volume of a box
- double Volume() const
- {
- return m_Length*m_Width*m_Height;
- }
- bool operator < (const CBox& aBox) const; // Overloaded 'less than'
- // Overloaded equality operator
- bool operator==(const CBox& aBox) const
- {
- return this->Volume() == aBox.Volume();
- }
- // Destructor definition
- ~CBox()
- {
- cout << "Destructor called." << endl;
- }
- 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
- };
- // Operator function for 'less than' that
- // compares volumes of CBox objects.
- inline bool CBox::operator < (const CBox& aBox) const
- {
- return this->Volume() < aBox.Volume();
- }
- int main()
- {
- CBox smallBox(4.0, 2.0, 1.0);
- CBox mediumBox(10.0, 4.0, 2.0);
- CBox bigBox(30.0, 20.0, 40.0);
- CBox thatBox(4.0, 2.0, 10.0);
- if(mediumBox < smallBox)
- cout << endl << "mediumBox is smaller than smallBox";
- if(mediumBox < bigBox)
- cout << endl << "mediumBox is smaller than bigBox";
- else cout << endl << "mediumBox is not bigger than bigBox";
- if(thatBox == mediumBox)
- cout << endl << “thatBox is equal to mediumBox”;
- else
- cout << endl << “thatBox is not equal to mediumBox”;
- cout << endl;
- return 0;
- }
示例说明
operator<()运算符函数的原型出现在类的public部分。由于函数定义在类定义外部,因此该函数默认不是内联函数,所以显式指定它。通常情况下最好把简单的演算法函数设置为内联的,这样代码运行速度会更快。把函数定义放在类定义外部的唯一原因是演示这种可能性。完全可以将函数定义放在类定义中,就像operator==()函数那样。这种情况下将不需要指定inline或者在函数名前面用CBox加以限定。我们记得,当函数成员在类定义外部定义时,为了告诉编译器该函数是CBox类的成员,必须用类名进行限定。
main()函数中有两条对类成员使用<运算符的if语句,它们将自动调用重载的运算符函数。如果想确认这一点,那么可以给运算符函数添加一条输出语句。此外还有一条使用==运算符的语句。该示例的输出如下:
- Constructor called.
- Constructor called.
- Constructor called.
- Constructor called.
- mediumBox is smaller than bigBox
- thatBox is equal to mediumBox
- Destructor called.
- Destructor called.
- Destructor called.
- Destructor called.
输出证实,使用运算符函数的if语句工作正常,重载的运算符可用于const和非const对象。因此直接用CBox对象表示CBox问题的解决方案开始成为很现实的命题。