编译器错误 C2679:没有找到接受“MyInteger”类型的右操作数的运算符(或没有可接受的转换)

博客介绍了C++编程中遇到的编译器错误C2679,该错误源于后置递增运算符的使用。在重载后置递增运算符时,由于返回的是临时对象,而友元函数的`operator<<`参数为普通引用,导致无法接受。解决方案是将`operator<<`的参数类型更改为常量引用。
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class MyInteger {
	friend ostream& operator<<(ostream& cout, MyInteger& myint);
private:
	int m_A;
public:
	MyInteger() {
		m_A = 0;
	}

	// 重载前置 ++ 运算符
	MyInteger& operator++() {
		++m_A;
		return *this;
	}

	// 重载后置++运算符 先将当前值返回,再进行递增运算
	 MyInteger operator++(int) {
		// 记录当前值
		MyInteger temp = *this;
		++*this;
		return temp;
	}
};

ostream& operator<<(ostream& cout, MyInteger& myint) {
	cout << myint.m_A;
	return cout;
}

void test01() {
	MyInteger myint;

	cout << ++(++myint) << endl;
	cout << myint << endl;
}

void test02() {
	MyInteger myint;
	cout << myint++ << endl;
	cout << myint << endl;
}

int main() {
	//test01();
	test02();

	//int& a = 10;
	//const int& b = 10;

	system("pause");
	return 0;
}

报错信息:

原因在于后置递增运算符:
为了区分前置递增运算符,在重载后置递增运算符的形参列表中添加了int占位符,而且由于后置递增不允许链式编程,其返回值类型为值类型,即返回一个临时对象,但是由于重载operator<<函数中接收的形参为普通引用,不能接收临时对象,所以才产生了这样的错误。

更改重载operator<<函数为(MyInteger类中友元函数声明中也要改):

ostream& operator<<(ostream& cout, const MyInteger& myint) {
	cout << myint.m_A;
	return cout;
}

将参数类型改为常量引用就能够正常输出了。

举例:

要注意区分普通引用和常量引用,最简单的例子就是:

	int& a = 10;    // 错误
	const int& b = 10; // 正确

对应到这个例子中:

	MyInteger& m1 = MyInteger();  // 错误,普通引用不能接收临时对象
	const MyInteger& m2 = MyInteger(); // 正确 常量引用能接收此临时对象
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值