作用:通过重载递增运算符,实现自己的整型数据
后置++:
//重载递增运算符
//自定义整形
class MyInt
{
friend ostream& operator<<(ostream& cout, MyInt myint);
public:
MyInt()
{
m_Num = 0;
}
//重载后置++运算符
//int代表占位参数,可以用于区分前置和后置
MyInt operator++(int)//注意这里返回值而不是引用
{
//先 记录当时结果
MyInt temp = *this;
//后 递增
m_Num++;
//最后返回记录结果
return temp;
}
private:
int m_Num;
};
//重载左移运算符
ostream& operator<<(ostream& cout, MyInt myint)
{
cout << myint.m_Num;
return cout;
}
void test02()
{
MyInt myint;
cout << myint++ << endl;
cout << myint << endl;
}
前置++:
//重载递增运算符
//自定义整形
class MyInt
{
friend ostream& operator<<(ostream& cout, MyInt myint);
public:
MyInt()
{
m_Num = 0;
}
//重载前置++运算符
//返回引用是为了一直对一个数据进行递增
MyInt& operator++()
{
//先递增
m_Num ++;
//再将自身作为返回
return *this;
}
private:
int m_Num;
};
//重载左移运算符
ostream& operator<<(ostream& cout, MyInt myint)
{
cout << myint.m_Num;
return cout;
}
void test01()
{
MyInt myint;
cout << ++myint << endl;
}