#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(); // 正确 常量引用能接收此临时对象
博客介绍了C++编程中遇到的编译器错误C2679,该错误源于后置递增运算符的使用。在重载后置递增运算符时,由于返回的是临时对象,而友元函数的`operator<<`参数为普通引用,导致无法接受。解决方案是将`operator<<`的参数类型更改为常量引用。
1029

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



