无法在C++中重载输出流

Not able to overload output stream in C++

本文关键字:重载 输出流 C++      更新时间:2023-10-16

我正试图重载<lt;我的类STEntry中的运算符,但一直遇到这个错误。我的课被贴在错误下面。

stentry.h: In function ‘std::ostream& operator<<(std::ostream&, const STEntry&)’:
stentry.h:48: error: no match for ‘operator<<’ in ‘std::operator<< [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((std::basic_ostream<char, std::char_traits<char> >&)((std::basic_ostream<char, std::char_traits<char> >*)out)), ((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)(& temp->STEntry::lexeme))) << ','’
stentry.h:46: note: candidates are: std::ostream& operator<<(std::ostream&, const STEntry&)

我在STEntry.h的课很简单。我试图显示一些可变值。

#ifndef __STENTRY__
#define __STENTRY__
#include <string>
using namespace std;
class STEntry {
  public:
     string lexeme; // addr. of lexema associated with this entry
     int  tokenval; // token value for this entry
     int  offset;   // location of variable in block
     STEntry(string name = "", int newval = 0, int newoffset = 0);
     // function:  constructor ... initializes major fields
     // Relational operators:
    bool operator == (const STEntry &) const;
    bool operator != (const STEntry &) const;
    friend ostream & operator << (ostream &, const STEntry &);
};
//--- BEGIN IMPLEMENTATION
//constructor
STEntry::STEntry(string name, int newval, int newoffset)
{
    lexeme = name;
    tokenval = newval;
    offset = newoffset;
}
// ....
//Output a single STEntry to standard output
std::ostream& operator << (std::ostream& out, const STEntry & temp)
{
    out << temp.lexeme << ',' << temp.tokenval << ',' << temp.offset;
    return out;
}
//--- END OF IMPLEMENTATION
#endif

您过载operator<<很好。正是函数内部的行导致了问题。

out << temp.lexeme << ',' << temp.tokenval << ',' << temp.offset;

从错误消息中,它不知道如何将lexeme(一个string)写入流中。

您是否同时包括<iostream><string>?我只在你发布的代码中看到其中一个。

添加

#include <iostream>

到您的文件。

您可能需要在标头之前包含iostream

您可能没有在项目中包含任何流库。尝试#include <iostream><ostream>

您实际上必须实现运算符<lt;换句话说,你必须写出来。

另外请注意,宏名称上的__是为编译器实现者保留的,不应使用。