c++重载自增与自减运算符(前置与后置)
生活随笔
收集整理的這篇文章主要介紹了
c++重载自增与自减运算符(前置与后置)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
運算符重載
要點:
1. 后置的運算符要帶一個整型參數(用來與前置運算符區分開)。
2.后置的返回值不要用引用(否則會因為是局部變量導致返回為一個不存在的值)。
3.再在置中要定義一個臨時變量來返回之前的值。
4.在后置運算符中可以使用前置運算符來簡化。
代碼(內有詳解)
#include <iostream> using namespace std;class point {public:point(int x1 = 0, int y1 = 0) {//構造函數,帶默認參數x = x1;y = y1;}int getx() {return x;}int gety() {return y;}void show() {//用來及時輸出值cout << x << "," << y;}point &operator ++();//重載的運算符point operator ++(int x);point &operator --();point operator --(int x);private:int x;int y;};point &point:: operator ++() {this->x++;this->y++;return *this; }point point::operator ++(int x ) {point p(*this);//定義一個臨時的類來保存加之前的值++(*this);//利用了重載的前置運算符return p; }point &point:: operator --() {this->x--;this->y--;return *this; }point point::operator --(int x ) {point p(*this);--(*this);return p; }int main() {int x, y;cin >> x >> y;point p(x, y);cout << "(" << p.getx() << "," << p.gety() << ")" << endl;cout << "(" ;p++.show();cout << ")" << endl;cout << "(" ;(++p).show() ;cout << ")" << endl;cout << "(" ;p--.show() ;cout << ")" << endl;cout << "(" ;(--p).show() ;//前置必須要加小括號cout << ")" << endl;return 0; }總結
以上是生活随笔為你收集整理的c++重载自增与自减运算符(前置与后置)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何实现运行时刻的多态?(c++)
- 下一篇: 基类与派生类之间的转换关系