// C9_1.cpp : Defines the entry point for the console application. // 覆載運算子,體積計算 #include "stdafx.h" #include // stream I/O 程式庫 using namespace std; class Rectangle // 類別定義 { public: double volumn1(); // 建構子定義 Rectangle(double ll = 1.0, double ww = 1.0, double hh = 1.0): m_length1(ll), m_width1(ww), m_height1(hh) { cout << endl << "建構子定義已被呼叫。"; } // 計算體積函式 double Volume() const { // 傳回立方體體積 return m_length1*m_width1*m_height1; } // 覆載 "大於" 運算子 bool operator>(const Rectangle& vBox) const; // 解構子定義 ~Rectangle() { cout << "解構子定義已被呼叫。" << endl; } private: double m_length1; // 長度,以公分為單位 double m_width1; // 寬度,以公分為單位 double m_height1; // 高度,以公分為單位 }; bool Rectangle::operator>(const Rectangle& vBox) const { return this->Volume() > vBox.Volume(); } // ******* main() 程式 ********************* int main(int argc, char* argv[]) { Rectangle Box1(6.0, 6.0, 1.0); Rectangle Box2(12.0, 6.0, 2.0); Rectangle Box3(26.0, 26.0, 40.0); cout << endl << "Box1 = " << Box1.Volume(); cout << endl << "Box2 = " << Box2.Volume(); cout << endl << "Box3 = " << Box3.Volume(); cout << endl << "-------------------------------------"; if(Box2 > Box1) // 未使用 Volume 函式 cout << endl << "Box2 大於 Box1"; if(Box2 > Box3) cout << endl << "Box2 大於 Box3"; else cout << endl << "Box2 不大於 Box3"; cout << endl; return 0; } double Rectangle::volumn1() { // 傳回立方體體積 * 2.0 return m_length1*m_width1*m_height1 * 2.0; }