C++编译错误C2679:binary '<<'无匹配T类型操作数求助
C++编译错误C2679修复方案
错误信息
Severity Code Description Project File Line Suppression State Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion)
错误触发行:
std::cout << "Popped Item: " << UniqueQueueDictionary->pop() << std::endl; // 错误行
问题原因
Queue::pop()返回的是Dictionary临时对象,但当前Dictionary类的operator<<重载声明为非const左值引用参数:
std::ostream& operator<<(std::ostream& ostr, Dictionary& D);
C++规则中临时对象无法绑定到非const左值引用,因此编译器找不到匹配的<<运算符,抛出C2679错误。同时Dictionary::display方法未声明为const成员函数,无法在const对象上调用,会进一步阻碍运算符重载的实现。
修复步骤
1. 更新Dictionary.h的运算符与方法声明
#ifndef DICTIONARY_H_ #define DICTIONARY_H_ #include <string> namespace sdds { class Dictionary { std::string m_term{}; std::string m_definition{}; public: const std::string& getTerm() const { return m_term; } const std::string& getDefinition() const { return m_definition; } Dictionary(const std::string& term, const std::string& definition) : m_term{ term }, m_definition{ definition }{} const std::string& getTermConst()const { return m_term; } Dictionary() : m_term{ "" }, m_definition{ "" }{}; // 修改为const成员函数 std::ostream& display(std::ostream& ostr = std::cout) const; }; bool operator==(const Dictionary& lhs, const Dictionary& rhs); // 修改为const引用参数 std::ostream& operator<<(std::ostream& ostr, const Dictionary& D); } #endif
2. 在Dictionary.cpp中实现正确的函数逻辑
#include "Dictionary.h" #include <iostream> namespace sdds { std::ostream& Dictionary::display(std::ostream& ostr) const { ostr << m_term << ": " << m_definition; return ostr; } std::ostream& operator<<(std::ostream& ostr, const Dictionary& D) { return D.display(ostr); } bool operator==(const Dictionary& lhs, const Dictionary& rhs) { return lhs.getTerm() == rhs.getTerm(); } }
验证效果
修改完成后,pop()返回的临时Dictionary对象可以正常通过<<运算符输出,同时Queue::display方法中遍历输出队列元素的逻辑也能正常编译运行。
内容的提问来源于stack exchange,提问作者sewrew swerew
相关产品推荐
相关产品推荐

