c++ --递减运算符重载
递减运算符重载原理其实和递增运算符重载相同,要了解原理可以去看我的递增运算符重载的文章,里面有递增运算符重载的注意事项和语法,这里只展示一下递减运算符的代码
#include<iostream>
#include<string>
using namespace std;
//递减运算符重载和递增运算符重载原理相同,只是运算符不一样
class Myint
{
public:
friend ostream& operator<<(ostream& cout, Myint my);
//前置递减运算符重载,函数声明
Myint& operator--();
Myint operator--(int);//同样需要使用占位参数来让编译器知道这是函数重载
public:
int num = 2;
};
Myint& Myint::operator--()
{
//自身先--
num--;
//然后返回自身
return *this;
}
Myint Myint::operator--(int)
{
//先创建一个临时对象来保存当前的值
Myint temp = *this;
num--;
return temp;
}
ostream& operator<<(ostream& cout, Myint my)//由于后置递减运算符返回的是值,所以左移运算符传入对象时,不使用引用
{
cout << "num的当前数值为:"<<my.num << endl;
return cout;
}
void test01()
{
Myint my;
cout << "前置递减运算符重载" << endl;
cout <<"前置递减" <<(--my) << endl;
cout <<"前置递减后my" <<my << endl;
}
void test02()
{
Myint my;
cout << "后置递减运算符重载" << endl;
cout << "后置递减前" << my << endl;
cout << (my--) << endl;
cout << "后置递减后" << my << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}