实现:
1、+号运算符重载
2、自定义输出数据类型,并实现递增,递减
#include<iostream>
#include<string>
using namespace std;
class mytype
{
friend ostream& operator<<(ostream& cout, mytype a);//友元让其可以访问mytype的私有成员
friend mytype operator+(mytype& a, mytype& b);
public:
mytype()//默认构造函数(无参构造函数)
{
m_num = 0;
}
mytype(int A)//有参构造函数
{
this->m_num = A;
}
/*重载递增运算符*/
mytype& operator++()//前置递增
{
m_num++;
return *this;
}
mytype operator++(int)//后置递增,加一个int占位符即可,返回的是一个值,不要返回一个局部变量的引用,用完就释放了
{
mytype temp = *this;//先记录一下当前的值,返回的也是这个值
this->m_num++;
return temp;
}
/*重载递减运算符*/
mytype& operator--()//前置递减,
{
m_num--;
return *this;
}
mytype operator--(int)//后置递减,返回的是一个值,不要返回一个局部变量的引用,用完就释放了
{
mytype temp = *this;
m_num--;
return temp;
}
private:
int m_num;
};
//重载<<输出运算符
ostream& operator<<(ostream& cout, mytype a)//本质:operator<<(cout,a); 最终简化成:cout<<a;
{
cout << a.m_num << endl;
return cout;
}
//重载+号运算符
mytype operator+(mytype& a,mytype& b)//本质:operator+(a, b);
{
mytype temp;
temp.m_num = a.m_num + b.m_num;
return temp;
}
void main()
{
//自定义输出数据类型,并实现递增,递减
mytype M;
cout << M;
++M; //本质:M.operator++();
cout << M;
--M;
cout << M;
cout << M++;
cout << M;
cout << M--;
cout << M;
//+号运算符重载
mytype M1;
mytype M2(10);
mytype M3(10);
M1 = M2 + M3;
cout << M1;
cout<<operator+(M1, M3);//简化成:cout<<M1+M3;
}