实现自己定义一种数据类型,并实现自增运算,
如:自定义myint类型,
myint a;
a++;
++a;
首先需要重载左移运算符,即可以输出自定义类型的数据,然后再实现自增
#include<iostream>
#include<string>
using namespace std;
class myint
{
friend ostream& operator<<(ostream& cout, myint a);
friend myint& operator++(myint &a);
friend myint& operator++(myint &a, int);
public:
myint()
{
}
private:
int m_a = 10;
};
ostream& operator<<(ostream& cout, myint a)
{
cout << a.m_a << endl;
return cout;
}
myint& operator++(myint &a)
{
a.m_a++;
return a;
}
myint& operator++(myint &a, int)
{
myint temp;
temp.m_a=a.m_a++;
return temp;
}
void main()
{
myint A;
cout << A << endl;
cout << ++A << endl;
cout << ++A << endl;
cout << A++ << endl;
cout << A << endl;
}