递增运算符重载
注意前置递增和后置递增在重载是的区别
#include <iostream>
using namespace std;
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);
public :
MyInteger()
{
m_num = 0 ;
}
MyInteger& operator++()
{
m_num++;
return *this;
}
MyInteger operator++(int)
{
MyInteger temp = *this;
m_num++;
return temp;
}
private:
int m_num;
};
ostream& operator<<(ostream& cout, MyInteger myint)
{
cout << myint.m_num;
return cout;
}
void test01()
{
MyInteger myint;
cout << myint << endl;
cout << ++(++myint) << endl;
cout << myint << endl;
}
void test02()
{
MyInteger myint;
cout << myint++ << endl;
cout << myint << endl;
}
int main()
{
cout << "前置递增重载" << endl;
test01();
cout << "后置递增重载" << endl;
test02();
cout << "\n " << endl;
system("pause");
return 0;
}
递减运算符重载
递减运算符和递增运算符的重载是一样的
#include <iostream>
using namespace std;
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
MyInteger()
{
m_num = 0;
}
MyInteger& operator--()
{
m_num--;
return *this;
}
MyInteger operator--(int)
{
MyInteger temp = *this;
m_num--;
return temp;
}
private:
int m_num;
};
ostream& operator<<(ostream& cout, MyInteger myint)
{
cout << myint.m_num;
return cout;
}
void test01()
{
MyInteger myint;
cout << myint << endl;
cout << --(--myint) << endl;
cout << myint << endl;
}
void test02()
{
MyInteger myint;
cout << myint-- << endl;
cout << myint << endl;
}
int main()
{
cout << "前置递减重载" << endl;
test01();
cout << "后置递减重载" << endl;
test02();
cout << "\n " << endl;
system("pause");
return 0;
}