我遇到了一个非常有趣的问题。
基本上我重载了插入运算符以返回我的类的字符串表示形式。但是,程序会终止,除非我包含一个 std::endl。
template<class T>
std::ostream& operator << (std::ostream& outs, const LinkedQueue<T>& q) {
outs << "queue[";
if (!q.empty()) {
outs << q.front->value;
for (auto i = ++q.begin(); i != q.end(); ++i)
outs << ',' << *i;
}
outs << "]:rear";
return outs;
}
int main() {
QueueType queueType1;
queueType1.enqueue("L");
std::cout << queueType1 << std::endl;
return 0;
}
上面的 main 产生了正确的输出:queue[L]:rear
但是,如果我从 main 中删除 std::endl
,程序就会中断并且不会产生任何结果。
我不能在重载方法中包含 endl
,因为它会向我的字符串添加一个我不知道的额外字符。有什么建议么?
最佳答案
正如@samevarshavchik 所建议的那样,使用std::flush
而不是std::endl
来完成所需的输出。这可以在 main 中完成:
int main() {
QueueType queueType1;
queueType1.enqueue("L");
std::cout << queueType1 << std::flush;
/*^^^here^^^*/
return 0;
}
或者在你的重载函数中:
template<class T>
std::ostream& operator << (std::ostream& outs, const LinkedQueue<T>& q) {
outs << "queue[";
if (!q.empty()) {
outs << q.front->value;
for (auto i = ++q.begin(); i != q.end(); ++i)
outs << ',' << *i;
}
outs << "]:rear" << std::flush;
/*^^^here^^^*/
return outs;
}
关于除非包含 endl,否则 C++ 重载的 << 运算符无法正确输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40252703/