无法在C++中重载输出流
Not able to overload output stream in C++
我正试图重载<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;换句话说,你必须写出来。
另外请注意,宏名称上的__是为编译器实现者保留的,不应使用。
相关文章:
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中编写 ostream 的向量,它接收所有不同的输出流,如 cout、ostringstream 和 ofs
- 在输出流中插入换行符
- 在类外部重载输入和输出流
- 通用容器的输出流
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 获取C++输出流中元素的大小
- 用于了解输入和输出流缓冲区实际工作方式的程序
- 控制多线程程序中的输出流
- 为什么输出流首选" "而不是""?
- C++ 输出流运算符 <<() 中的字符何时加宽?
- 音频缓冲区列表,用于输出流格式已压缩的 AUHAL 单元
- 输出流运算符的重载
- 重载类的输出流运算符
- 为我自己的类重载输出流
- C++ 编译器选择输出流运算符<<的错误重载
- 如何将 vector 传递给将自定义对象作为参数的重载输出流
- 无法在C++中重载输出流
- 在模板外部重载模板类的输出流操作符