[Lang] 運算子過載

yaoguyuan發表於2024-08-15

[Lang] 運算子過載

#include<iostream>
using namespace std;

class MyInt {
    friend ostream &operator<<(ostream &os, const MyInt &myint);
    friend istream &operator>>(istream &is, MyInt &myint);
private:
    int val;
public:
    MyInt() : val(0) {}
    MyInt(int val) : val(val) {}
    MyInt &operator++() {
        val++;
        return *this;
    }
    MyInt operator++(int) {
        MyInt temp = *this;
        val++;
        return temp;
    }
};

ostream &operator<<(ostream &os, const MyInt &myint) {
    os << myint.val;
    return os;
}
istream &operator>>(istream &is, MyInt &myint) {
    is >> myint.val;
    return is;
}

int main() {
    MyInt a, b;
    cin >> a >> b;
    cout << ++(++a) << endl;
    cout << (b++)++ << endl;
    return 0;
}
PS D:\CppDev\Lang\overload> cd "d:\CppDev\Lang\overload\" ; if ($?) { g++ test1.cpp -o test1 } ; if ($?) { .\test1 }
10 20
12
20

1. 遞增運算子

(1) 前置遞增

  • 返回值必須為引用,否則++(++a)後a的值將與預期不一致

(2) 後置遞增

  • 返回值不能為引用,否則將導致懸空指標問題

  • 佔位符int表示後置單目運算子,用於實現函式過載

2. 移位運算子

  • 必須由普通函式過載,否則順序將與預期不一致
  • 必須返回標準輸出流或標準輸入流自身,否則將無法實現級聯
  • 由於是類外函式,必須在類內宣告友元

相關文章