gpt4 book ai didi

除非包含 endl,否则 C++ 重载的 << 运算符无法正确输出

转载 作者:太空狗 更新时间:2023-10-29 22:58:30 25 4
gpt4 key购买 nike

我遇到了一个非常有趣的问题。

基本上我重载了插入运算符以返回我的类的字符串表示形式。但是,程序会终止,除非我包含一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com