2016-10-26 11 views
3

꽤 흥미로운 문제입니다.endlo을 포함하지 않으면 C++에 과부하 된 << 연산자가 올바르게 출력되지 않습니다.

기본적으로 나는 삽입 연산자를 오버로드하여 클래스의 문자열 표현을 반환합니다. 그러나 std :: endl을 포함하지 않으면 프로그램이 종료됩니다. 큐 [L] :

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::endl를 제거하는 경우 프로그램 바꿈 아무것도 발생하지 않는다.

과부하 메서드에 endl을 포함 할 수 없습니다. 내 문자열에 추가 문자를 추가했기 때문에이 문자열을 포함 할 수 없습니다. 어떤 제안?

+5

당신은 착각이다. 표시된 코드에는 아무런 문제가 없지만 원하는 경우'outs << std :: flush; '를 사용하여 명시 적으로 스트림 버퍼를 플러시 할 수 있습니다. –

+0

https://stackoverflow.com/questions/22026751/c-force-stdcout-flash-print-to-screen에 중복 – Mine

답변

1

@samevarshavchik에서 제시하는대로 std::endl 대신 std::flush을 사용하여 원하는 결과를 얻으십시오. 이 메인으로 수행 할 수 있습니다

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; 
}