C++ 運算子過載練習
阿新 • • 發佈:2018-12-19
總時間限制:
1000ms
記憶體限制:
65536kB
// 在此處補充你的程式碼
描述
程式填空
#include <iostream> using namespace std; class MyInt { int nVal; public: MyInt( int n) { nVal = n ;}
}; int Inc(int n) { return n + 1; } int main () { int n; while(cin >>n) { MyInt objInt(n); objInt-2-1-3; cout << Inc(objInt); cout <<","; objInt-2-1; cout << Inc(objInt) << endl; } return 0; }
輸入
多組資料,每組一行,整數n
輸出
對每組資料,輸出一行,包括兩個整數, n-5和n - 8
樣例輸入
20 30
樣例輸出
15,12 25,22
來源
Guo Wei
這裡涉及一個減法過載和int()過載, 有意思的是int()過載在寫的時候不用寫前面的返回值,否則會報錯,直接看程式碼
#include <iostream> using namespace std; class MyInt { int nVal; public: MyInt(int n) { nVal = n; } // 在此處補充你的程式碼 MyInt& operator -(int n) { nVal -= n; return *this; } operator int() { return nVal; } }; int Inc(int n) { return n + 1; } int main() { int n; while (cin >> n) { MyInt objInt(n); objInt - 2 - 1 - 3; cout << Inc(objInt); cout << ","; objInt - 2 - 1; cout << Inc(objInt) << endl; } return 0; }