C++/c++ basic

8. 입출력 연산자 오버로딩

safy 2022. 12. 21. 13:43
728x90
반응형

이전 글

2022.12.21 - [C++/c++ basic] - 7. 이항 연산자 오버로딩

 

7. 이항 연산자 오버로딩

이전 글 2022.12.21 - [C++/c++ basic] - 6. Wrapper 클래스 - 타입변환 연산자 6. Wrapper 클래스 - 타입변환 연산자 이전 글 & 참고 글 2022.12.21 - [분류 전체보기] - 5. 연산자 오버로딩, friend 키워드 5. 연산자 오

projecthub.tistory.com

참고 글

2022.12.21 - [C++/c++ basic] - 5. 연산자 오버로딩, friend 키워드

 

5. 연산자 오버로딩, friend 키워드

이전 글 2022.12.21 - [C++/c++ basic] - 4. implicit, explicit, mutable 키워드 4. implicit, explicit, mutable 키워드 이전 글 2022.12.21 - [C++/c++ basic] - 3. copy consturctor 3. copy consturctor 이전 글 2022.12.21 - [C++/c++ basic] - 2. refer

projecthub.tistory.com


입출력 연산자 오버로딩

 

std::cout << s;

라고 하는 것은 std::cout.operator<<(s) 를 하는 것과 동일한 명령. (ostream 클래스에 정의되어 있다.)



아래는 friend를 활용해 ostream의 클래스 연산자 함수를 추가해본 것이다.

ostream의 코드를 수정할 수 없으므로 

 

ostream 클래스 객체와 임의로 정의한 CComplex 객체 두 개를 인자로 받는 전역 opreator<< 함수를 정의하였다.

class CComplex
{
    ...
    friend std::ostream& operator<<(std::ostream& os, const CComplex& complex);
};
 
...
 
std::ostream& operator<<(std::ostream& os, const CComplex* complex)
{
    os << "(" << complex.m_real << ", " << complex.m_Img << ")";
    return os;
}
728x90
반응형