C++實現前置和後置++,--
阿新 • • 發佈:2021-01-13
前置和後置++,–
題目描述:
定義一個Point類要求實現對點的前置和後置++,–
首先要明確,前置和後置++,–的計算過程
++i //表示i值直接加1,然後進行後續操作比如輸出
i++ //表示先進行後續操作比如輸出,再i+1
–的過程和上面類似
#include<iostream> using namespace std; class Point { private: int x,y; public: Point()=default; Point(int x,int y):x(x),y(y){} Point &operator++(); //注意這裡的寫法,這表示前置++ Point operator++(int); //這表示後置++ Point &operator--(); Point operator--(int); void show(){ cout<<x<<","<<y<<endl; } }; Point &Point::operator++() { x++; y++; return *this; } Point Point::operator++(int) { Point old=*this; ++(*this); return old; //後置++,把原來的值返回 } Point &Point::operator--() { x--; y--; return *this; } Point Point::operator--(int) { Point old=*this; --(*this); return old; } int main() { Point c1(2,3),c2; c1.show(); c2=c1++; c2.show(); c2=++c1; c2.show(); c2=c1--; c2.show(); }
結果
2,3
2,3
4,5
4,5