C++的递增运算符重载
用途:主要用来实现自义定数据类型的递增
实现递增重载前,为了可以cout直接输出自定义数据类型先实现一下左移运算符(<<)的递增。
实现左移递增
#include <iostream>
#include <string>
using namespace std;
class MyIntger
{
friend ostream& operator<<(ostream &cout, MyIntger& myint);//考虑到m_nums是私有的,用友元。
private:
int m_num;
public:
MyIntger(/* args */);
~MyIntger();
};
MyIntger::MyIntger(/* args */)
{
int m_num=0;//在构造的时候初始化
}
MyIntger::~MyIntger()
{
}
ostream& operator<<(ostream &cout, MyIntger& myint)//在类内重载左移不能实现需要的结果,所以用全局函数重载左移。
{//因为cout对象只能有一份,所以用引用。
cout<<myint.m_num;
return cout;//返回引用
}
int main() {
MyIntger myint;
cout<<myint;
system("pause");
}
前置递增的重载
#include <iostream>
#include <string>
using namespace std;
class MyIntger
{
friend ostream& operator<<(ostream &cout, MyIntger& myint);
private:
int m_num;
public:
MyIntger(/* args */);
~MyIntger();
MyIntger& operator++()//在类内实现前置++的重载
{
m_num++;
return *this;//**通过this返回当前的对象的引用**
}
};
MyIntger::MyIntger(/* args */)
{
int m_num=0;
}
MyIntger::~MyIntger()
{
}
ostream& operator<<(ostream &cout, MyIntger& myint)
{
cout<<myint.m_num;
return cout;
}
int main() {
MyIntger myint;
cout<<++myint;
system("pause");
}
后置递增的重载
#include <iostream>
#include <string>
using namespace std;
class MyIntger
{
friend ostream& operator<<(ostream &cout, const MyIntger& myint);
private:
int m_num;
public:
MyIntger(/* args */);
~MyIntger();
MyIntger& operator++()
{
m_num++;
return *this;
}
MyIntger operator++(int)//后置++重载
{
MyIntger temp=*this;//拷贝构造,保存之前的状态
m_num++;
return temp;
}
};
MyIntger::MyIntger(/* args */)
{
int m_num=0;
}
MyIntger::~MyIntger()
{
}
ostream& operator<<(ostream &cout, const MyIntger& myint)
{
cout<<myint.m_num;
return cout;
}
int main() {
MyIntger myint;
cout<<myint++;
system("pause");
}
注意:
1.使用int占位的是后置递增重载,而在前置递增重载中并没有用到占位,因为C++中根据函数参数的不同实现了operator++函数的重载。而此时函数的返回类型也由MyIntger&引用的方式变成了值,该值是未加1时的状态。实现了先返回而后递增。
MyIntger operator++(int)//
{
MyIntger temp=*this;//拷贝构造,保存之前的状态
m_num++;
return temp;
}
2.在写后置递增的时候发现在左移重载那里会报错,于是将左移重载函数的第二个参数加了const。
ostream& operator<<(ostream &cout, const MyIntger& myint)
{
cout<<myint.m_num;
return cout;
}
原因:
因为在cout<<myint++的时候相当于调用“ostream& operator<<(ostream &cout, const MyIntger& myint)”函数,而myint++作为它第二个参数传入,myint++也相当于调用了“MyIntger operator++(int)”结果是一个值类型的返回,而这个值本身是只读的。所以在调用operator<<函数时,形参得加const。
本文介绍了C++如何重载递增运算符,包括前置递增和后置递增的实现方式。在实现自定义数据类型的递增功能时,还需要注意函数返回类型和参数的区别,以及在后置递增中遇到的问题,如左移运算符重载时的const限定问题。

8056

被折叠的 条评论
为什么被折叠?



