递增与算符的重载分为前置++,和后置++;
前置++的重载
using namespace std;
class Person
{
public:
//Person &operator++()//类内,&的作用实现连续++;
//{
// m_age++;
// return *this;
//}
int m_age;
};
Person &operator++(Person& p)//类外
{
p.m_age++;
return p;
}
void test01()
{
Person p1;
p1.m_age = 20;
++(++p1);
cout << p1.m_age << endl;
}
int main()
{
test01();
return 0;
}
后置++的重载
class Person
{
public:
//Person operator++(int)//类内
//{
// Person tmp = *this;
// m_age++;
// return tmp;
//}
int m_age;
};
Person operator++(Person& p,int)//类外
{
Person tmp = p;
p.m_age++;
return tmp;
}
void test01()
{
Person p1;
p1.m_age = 20;
p1++;
cout << p1.m_age << endl;
}
int main()
{
test01();
return 0;
}