整理一下最近学的重载运算符前加后加,前减后减的问题 ⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄
前加前减情况:
#include <iostream>
using namespace std;
class Int {
private:
int num;
public:
Int(int n) {
num = n;
}
operator ++ () {
(*this).num++;
return (*this).num;
}
operator -- () {
(*this).num--;
return (*this).num;
}
};
int main() {
Int c(2);
cout << ++c << endl;
cout << --c << endl;
return 0;
}
这样的话输出结果是:
3
2
后加后减情况:
#include <iostream>
using namespace std;
class Int {
private:
int num;
public:
Int(int n) {
num = n;
}
operator ++ (int) {
Int temp = *this;
(*this).num++;
return temp.num;
}
operator -- (int) {
Int temp = *this;
(*this).num--;
return temp.num;
}
};
int main() {
Int c(2);
cout << c++ << endl;
cout << c-- << endl;
return 0;
}
这样的话输出结果是:
2
3