'<< 오퍼레이터, >> 오퍼레이터' 오버로딩


<< 연산자의 이름이 double shift라고 막연히 생각했는데, insertion operator 라는 충격적인 사실을 알게 되었다. 마찬가지로 >> 도 extraction operator라는 이름을 가지고 있었다. 


# C++의 표준 입출력 스트림 객체와 함께 사용되는 연산자  >> , <<

1) >> operator :  extraction operator

2) << operator :  insertion operator 


이를 위해, msdn 의 차료를 참고해서 공부를 해보자.



1. >> operator  오버로딩(Input stream - extraction operator)


Input streams use the extraction (>>) operator for the standard types. You can write similar extraction operators for your own types; your success depends on using white space precisely.

Here is an example of an extraction operator for the Date class presented earlier:

istream& operator>> ( istream& is, Date& dt )  
{  
   is >> dt.mo >> dt.da >> dt.yr;  
   return is;  
}  


이 경우에는 return by address를 통해서 istream 객체를 반환하여 chaining을 지원하여 1) is >> dt.mo, 2) is > >dt.da , 3) is >> dt.yr 순으로 실행된다.




2. << operator  오버로딩


Output streams use the insertion (<<) operator for standard types. You can also overload the << operator for your own classes.

The write function example showed the use of a Date structure. A date is an ideal candidate for a C++ class in which the data members (month, day, and year) are hidden from view. An output stream is the logical destination for displaying such a structure. This code displays a date using the cout object:

Date dt( 1, 2, 92 );  
cout << dt;  

To get cout to accept a Date object after the insertion operator, overload the insertion operator to recognize an ostream object on the left and a Date on the right. The overloaded << operator function must then be declared as a friend of class Date so it can access the private data within a Date object.

// overload_date.cpp // compile with: /EHsc #include <iostream> using namespace std; class Date { int mo, da, yr; public: Date(int m, int d, int y) { mo = m; da = d; yr = y; } friend ostream& operator<<(ostream& os, const Date& dt); // friend 키워드를 통해 directly access data 가능 }; ostream& operator<<(ostream& os, const Date& dt) // 오퍼레이터 오버로딩 { os << dt.mo << '/' << dt.da << '/' << dt.yr; // 예를 들면 5/6/92 와 같이 출력 return os; } int main() { Date dt(5, 6, 92); cout << dt; }

5/6/92

The overloaded operator returns a reference to the original ostream object, which means you can combine insertions:

cout << "The date is" << dt << flush;  


https://msdn.microsoft.com/ko-kr/library/1z2f6c2k.aspx

'C++' 카테고리의 다른 글

오버로딩 Vs 오버라이딩  (0) 2018.02.19
증감연산자 오버로딩  (0) 2018.02.18
파일스트림 입출력  (0) 2018.02.17
배열  (0) 2018.02.17
디폴트 인수  (0) 2018.02.16

+ Recent posts