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

标签 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 << 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/

相关文章:

c++ - WINAPI 光标在应用程序窗口上的单击位置

javascript - Emscripten Uncaught RangeError : Source is too large, 多个 Float32Arrays

kotlin - Kotlin 中的运算符重载

c++ - 如何为具有 2 个变量的对象重载 C++ 中的增量运算符?

c++ - 防止 CMake 为仅可选 header 库生成的 makefile 在仅 header 模式下编译源文件

c++ - 定义仅由某个类需要的结构的最佳方法是什么?

c++ - 重载运算符时出错(必须是非静态成员函数)

wpf - 使用 UpdateSourceTrigger=PropertyChanged 绑定(bind)到 Decimal 的 TextBox

c# - 获取错误的日期时间格式

c# - 如何在 .NET 中将数字格式化为固定的字符串大小?