当我想自己实现通过重载递增运算符,实现自己的整形数据的递增时,出现了以下错误:
[Error] cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
以下是运行错误的代码:
//递增运算符重载
#include<iostream>
using namespace std;
class MyInteger{
friend ostream & operator <<(ostream &cout,MyInteger &p);
public:
MyInteger(){
m_Num=0;
}
//前置++
MyInteger & operator ++(){
m_Num++;
return *this;
}
//后置++
MyInteger operator ++(int){
MyInteger temp=*this;//*this代表当前本身的值
m_Num++;
return temp;
}
private:
int m_Num;
};
ostream & operator <<(ostream & cout,MyInteger &p){
cout<<p.m_Num<<endl;
return cout;
}
void text01(){
MyInteger myint;
cout<<++myint<<endl;
cout<<myint<<endl;
}
void text02(){
MyInteger myint;
cout<<myint++<<endl;
cout<<myint<<endl;
}
int main(){
text01();
text02();
return 0;
}
原因是在text02函数中,在运行myint++时返回的是temp,temp是一个局部变量,在栈区,运行结束后就会被释放掉,则如果用引用传递的话就会指向空内存,因此在ostream & operator <<(ostream & cout,MyInteger &p)函数中p不应该进行引用传递,应该进行值传递,所以把函数中的MyInteger &p改为MyInteger p即可。
初学者,如有错误还请各位大佬不吝赐教。