1.前置运算符重载
#include <iostream>
#include <string>
using namespace std;
class myInt
{
friend ostream& operator<<(ostream &cout, myInt &m1);
public:
myInt()
{
m_A = 10;
}
//前置递增
myInt& operator++()
{
//先增加
++m_A;
//再返回值
return *this;
}
private:
int m_A;
};
ostream& operator<<(ostream &cout,myInt &m1)
{
cout << m1.m_A << endl;
return cout;
}
void test01()
{
myInt m1;
cout << ++m1 << endl;
cout << m1 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
2.后置运算符重载
#include <iostream>
#include <string>
using namespace std;
class myInt
{
friend ostream& operator<<(ostream &cout, myInt m1);
public:
myInt()
{
m_A = 10;
}
//后置递增
myInt operator++(int)
{
//保存当前值
myInt temp = *this;
//++运算符
m_A++;
//返回保存值
return temp;
}
private:
int m_A;
};
ostream& operator<<(ostream &cout,myInt m1)
{
cout << m1.m_A << endl;
return cout;
}
void test01()
{
myInt m1;
cout << m1++ << endl;
cout << m1 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}