2011-09-12 4 views
2

IO 연산자 오버로드와 관련된 일부 C++ 코드를 테스트하고 있습니다. 코드로 다음과C++에서 입출력 연산자를 오버로드 할 때 cout/cin을 사용합니까?

class Student { 
private: 
    int no; 
public: 
    Student(int n) 
    { 
     this->no = n; 
    } 
    int getNo() const { 
     return this->no; 
    } 
    friend istream& operator>>(istream& is, Student& s); 
    friend ostream& operator<<(ostream& os, const Student& s); 
}; 
ostream& operator<<(ostream& os, const Student& s){ 
    cout << s.getNo(); // use cout instead of os 
    return os; 
} 
istream& operator>>(istream& is, Student& s) 
{ 
    cin >> s.no; // use cin instead of is 
    return is; 
} 

을 그러나 <<>> 내부 I 사용할 수

ostream& operator<<(ostream& os, const Student& s){ 
    os << s.getNo(); // use os instead of cout 
    return os; 
} 
istream& operator>>(istream& is, Student& s) 
{ 
    is >> s.no; // use is instead of cin 
    return is; 
} 

<<에서, I는 OS 대신 COUT 및 >> 연산자 유사성 객체를 사용. 그래서, 그 차이가 있는지 궁금합니다.

답변

5

차이점은 명백한데,/os는 입출력 스트림이고 cin/cout은 표준 입출력 스트림입니다. cin/cout은 동의어가 아닌 입출력 스트림의 인스턴스입니다.

요점은 파일, 문자열 스트림 및 사용자가 생각할 수있는 모든 사용자 지정 구현과 같은 표준 입력/출력 이외의 스트림이 있다는 것입니다. 당신이 스트림을 무시하고, 스트리밍 사업자에 착/cout을 사용하는 경우 그들은/오히려 그에게 가정 파일에보다, 당신은 표준 출력에

file_stream << some_student; 

인쇄 될 겁니다, 쓰기 읽어야 .

+0

표준 입력/출력 스트림이란 무엇입니까? "실행을 시작할 때 컴퓨터 프로그램과 그 환경 (일반적으로 텍스트 터미널) 사이에 미리 연결된 입출력 채널입니다"(http://en.wikipedia.org/wiki/Standard_streams) ?? – ipkiss

+0

오른쪽에 대한 소리. –

+0

지금은 분명합니다. 고마워. – ipkiss

관련 문제