#include<iostream>
using namespace std;
class Complex
{
public:
friend Complex& operator++(Complex &tmp);
friend Complex operator++(Complex &tmp, int);
Complex(int a=0, int b=0)
{
this->a = a;
this->b = b;
}
//成员函数实现 前置--
Complex operator--()
{
this->a--;
this->b--;
cout << "a="<<a <<" b="<<b<< endl;
return *this;
}
Complex& operator--(int)
{
Complex tmp = *this;
this->a--;
this->b--;
return tmp;
}
void printfm()
{
cout << this->a<< endl;
cout <<this->b << endl;
}
private:
int a;
int b;
};
//全局函数实现前置++
Complex& operator++(Complex &tmp)
{
tmp.a++;
tmp.b++;
cout <<"a="<<tmp.a <<" b="<<tmp.b<< endl;
return tmp;
}
//全局函数实现后置++
Complex operator++(Complex &tmp,int)
{
Complex c = tmp;
tmp.a++;
tmp.b++;
return c;
}
void main()
{
Complex c1(1, 1);
Complex c2(2, 2);
//全局函数实现前置++
Complex c3=operator++(c1);
//成员函数实现前置--
Complex c4(5,5);
c4.operator--();
//全局函数实现后置++
Complex c5(7, 7);
//c5.printfm();
Complex c6=c5++;
c6.printfm();//输出为 7 ,7
//成员函数实现后置--
Complex c7(9, 9);
Complex c8=c7--;
c8.printfm();
c7.printfm();
system("pause");
}
C++ 一元运算符的重载(前置++ --,后置 ++ --)
猜你喜欢
转载自blog.csdn.net/error0_dameng/article/details/82116253
今日推荐
周排行