[Error] cannot bind ‘std::ostream {aka std::basic_ostream<char>}‘ lva

本文介绍了在C++中尝试通过重载前置和后置递增运算符实现自定义整型类时遇到的问题。错误提示表明在使用引用传递时,返回的临时对象在函数调用结束后被释放,导致引用失效。解决方案是将`ostream& operator<<(ostream& cout, MyInteger& p)`函数中的参数改为值传递,以避免空引用。作者作为初学者,欢迎指正。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我想自己实现通过重载递增运算符,实现自己的整形数据的递增时,出现了以下错误:

[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即可。

初学者,如有错误还请各位大佬不吝赐教。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值