操作符重载和复制构造函数,右++是有参数的,左++是没有参数的。
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <list>
#include <deque>
#include <iostream>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <string>
using namespace std;
class Point
{
private:
int x;
public:
Point(int x1)
{ x=x1;}
Point operator++();//成员函数定义自增
const Point operator++(int x); //后缀可以返回一个const类型的值
friend Point operator--(Point& p);//友元函数定义--
friend const Point operator--(Point& p,int x);//后缀可以返回一个const类型的值
Point(const Point &C){x=C.x;}
Point operator=(Point C){
printf("hello\n");
Point *cc=new Point(C.x);
return *cc;
}
int show(){return x;}
};
Point Point::operator++()//++obj
{
printf("left ++\n");
x++;
return *this;
}
const Point Point::operator++(int x)//obj++
{
printf("right ++\n");
Point temp = *this;
this->x++;
return temp;
}
Point operator--(Point& p)//--obj
{
p.x--;
return p;
//前缀形式(--obj)重载的时候没有虚参,通过引用返回*this 或 自身引用,也就是返回变化之后的数值
}
const Point operator--(Point& p,int x)//obj--
{
Point temp = p;
p.x--;
return temp;
// 后缀形式obj--重载的时候有一个int类型的虚参, 返回原状态的拷贝
}
int main()
{
Point a(1);
Point b(0);
Point c(0);
a++;//隐式调用成员函数operator++(0),后缀表达式
++a;//隐式调用成员函数operator++(),前缀表达式
b--;//隐式调用友元函数operator--(0),后缀表达式
--b;//隐式调用友元函数operator--(),前缀表达式
/*
printf("a.data=%d\n",a.show());
b=a++;
printf("a.data=%d\n",b.show());
c=++a;
printf("a.data=%d\n",c.show());
*/
/*
cout<<a.operator ++(2);//显式调用成员函数operator ++(2),后缀表达式
cout<<a.operator ++();//显式调用成员函数operator ++(),前缀表达式
cout<<operator --(b,2);//显式调用友元函数operator --(2),后缀表达式
cout<<operator --(b);//显式调用友元函数operator --(),前缀表达式 </PRE>
*/
return 0;
}