C++ C++;超载<&书信电报;运算符不能正确输出,除非我包含endl
我有一个很有趣的问题 基本上,我重载了插入操作符以返回类的字符串表示形式。但是,除非包含std::endl,否则程序将终止C++ C++;超载<&书信电报;运算符不能正确输出,除非我包含endl,c++,operator-overloading,string-formatting,endl,C++,Operator Overloading,String Formatting,Endl,我有一个很有趣的问题 基本上,我重载了插入操作符以返回类的字符串表示形式。但是,除非包含std::endl,否则程序将终止 template<class T> std::ostream& operator << (std::ostream& outs, const LinkedQueue<T>& q) { outs << "queue["; if (!q.empty()) { outs &
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;
}
模板
std::ostream&operator正如@samevarshavchik所建议的,使用std::flush
而不是std::endl
来完成所需的输出。这主要可以通过以下方式完成:
int main() {
QueueType queueType1;
queueType1.enqueue("L");
std::cout << queueType1 << std::flush;
/*^^^here^^^*/
return 0;
}
intmain(){
队列类型队列类型1;
排队类型1.排队(“L”);
std::您可能弄错了。显示的代码没有问题,但是,如果您愿意,您可以使用out复制
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;
}