3

我遇到的非常有趣的问题。

基本上我正在重载插入运算符以返回我的类的字符串表示形式。但是,除非我包含 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

但是,如果我std::endl从 main 中删除,程序会中断并且什么也不会产生。

我不能endl在重载方法中包含一个,因为它在我的字符串中添加了一个额外的字符,而我没有这样做。有什么建议么?

4

1 回答 1

1

正如@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;
}
于 2016-10-26T05:02:18.347 回答