主函数:
#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 的顺序输出,得到的结果不一样????????????