76 lines
1007 B
C++
76 lines
1007 B
C++
// 运算符重载
|
|
// ++、-- 运算符
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
|
|
using namespace std;
|
|
|
|
class A
|
|
{
|
|
private:
|
|
int x;
|
|
|
|
public:
|
|
explicit A(int x)
|
|
{
|
|
this->x = x;
|
|
}
|
|
void show()
|
|
{
|
|
cout << x << endl;
|
|
}
|
|
// ++ 运算符重载,类成员函数,单目运算符,++ 在前时不要参数,++ 在后需要一个占位参数
|
|
A &operator++(int);
|
|
A &operator++();
|
|
A *operator--(int);
|
|
A *operator--();
|
|
};
|
|
|
|
A &A::operator++(int) // ++ 在后需要有占位参数
|
|
{
|
|
this->x++;
|
|
return *this;
|
|
}
|
|
|
|
A &A::operator++()
|
|
{
|
|
++this->x;
|
|
return *this;
|
|
}
|
|
|
|
A *A::operator--(int)
|
|
{
|
|
A *tmp = new A(this->x--);
|
|
return tmp;
|
|
}
|
|
|
|
A *A::operator--()
|
|
{
|
|
A *tmp = new A(--this->x);
|
|
return tmp;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
A a1(5);
|
|
a1.show();
|
|
a1++;
|
|
a1.show();
|
|
++a1;
|
|
a1--;
|
|
a1.show();
|
|
--a1;
|
|
a1.show();
|
|
|
|
A a2(8);
|
|
a2--;
|
|
a2--;
|
|
a2++;
|
|
++a2;
|
|
--a2;
|
|
a2.show();
|
|
|
|
return 0;
|
|
}
|