[Lang] 运算符重载

[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. 移位运算符

  • 必须由普通函数重载,否则顺序将与预期不一致
  • 必须返回标准输出流或标准输入流自身,否则将无法实现级联
  • 由于是类外函数,必须在类内声明友元
posted @ 2024-08-15 01:03  yaoguyuan  阅读(4)  评论(0编辑  收藏  举报