主函式:
#include "stdafx.h"
#include"Point.h"
#include<iostream>
int main()
{
point a(3,4);
point b(3,4);
point c(3,4);
cout<<a<<"--"<<(++a)<<"---- "<<(a++)<<endl; //先執行的是后置++; 然后執行的是前置++
cout<<(b++)<<"-- "<<(++b)<<"---- "<<(b)<<endl; //這個先執行的是前置++;
cout<<(c++)<<"-- "<<(c)<<"---- "<<(++c)<<endl; //這個先執行的是前置++;
return 0;
}
類的:
#ifndef _Point_h_
#define _Point_h_
#include "stdafx.h"
#include<iostream>
using namespace std;
class point
{
public:
point(double m,double n);
~point(){};
point& operator ++();
point operator ++(int);
point& operator --();
point operator --(int);
friend ostream& operator << (ostream& o,point& p);
private:
double x;
double y;
};
#endif
類的實作:
#include "stdafx.h"
#include"Point.h"
#include<iostream>
#include<ostream>
using namespace std;
//函式的實作
point::point(double m,double n)
{ x=m;
y=n;
}
point& point:: operator ++() //如果回傳值不是應用,就不能進行取址運算,只是一個臨時變數。++a=5
{
++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;
}
ostream& operator <<(ostream& o,point& p)
{
o<<"("<<p.x<<","<<p.y<<")";
return o;
}
輸出結果:

為什么相同的初始值Point a b c; 通過不同 a++,++a,a 的順序輸出,得到的結果不一樣????????????
uj5u.com熱心網友回復:
這是未定義行為啊。不要寫類似的代碼,++ --要單獨寫一個陳述句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/80997.html
標籤:基礎類
上一篇:論壇上下載了 C++Builder6.0 Help檔案 不知道怎么安裝到軟體里?
下一篇:vs 2015 動態庫呼叫問題
