C++重载<<与++运算符报错E0349:无匹配运算符,求排查
问题分析与解决:C重载<<和运算符的编译错误
错误原因
报错E0349: no operator "<<" matches these operands的核心原因是类型不匹配:
- 后置
operator++(int)返回的是一个临时K对象(右值)——因为后置++需要先返回对象当前值,再执行自增,必须创建临时副本返回。 - 你定义的
operator<<第二个参数是K&(非const左值引用),C++语法规定非const左值引用无法绑定到右值(临时对象),因此编译器找不到能处理cout << 临时K对象的重载版本。
解决方法
将operator<<的第二个参数改为const左值引用,这样既符合输出操作不修改对象的逻辑,又能兼容左值和右值(临时对象可以绑定到const左值引用)。
修改后的代码
#include <iostream> #include <string> using namespace std; class K { int x, y; public: K(int a, int b) :x(a), y(b) {}; K() :x(0), y(0) {}; K operator++(int); K& operator++(); // 修改:参数添加const friend ostream& operator<< (ostream & str, const K & obj); }; K K::operator++(int) { K temp(*this); x += 1; y += 1; return temp; } K& K::operator++() { x += 1; y += 1; return *this; } // 修改:参数添加const ostream& operator<<(ostream& str, const K& obj) { str << "[" << obj.x << ", " << obj.y << "]"; return str; } int main(int argc, char* argv[]) { K obj{10, 20}; cout << obj++ << endl; // 现在可以正常编译 cout << obj << endl; cout << ++obj << endl; }
补充说明
前置operator++()返回的是K&(左值引用),指向原对象,所以即使原来的operator<<参数是非const引用也能匹配,这就是cout << ++obj之前没有报错的原因。
内容的提问来源于stack exchange,提问作者never_ever
相关产品推荐
相关产品推荐

