C++/C++ 이론
[C++] << 연산자 오버로딩
renne
2022. 8. 24. 21:57
cout << 의 동작 방법
#include <iostream>
using namespace std;
int main(){
int x = 1;
int y = 2;
cout << x << y << endl;
(cout << x) << y;
return 0;
}
/*
<실행 결과>
12
12
*/
- cout은 왼쪽에서 오른쪽으로 구문을 읽는다.
- << 연산자는 x를 출력하고, 다시 괄호로 (cout << x) 이렇게 묶여서 y를 출력한다.
- 따라서, << 연산자는 iostream에 정의되어 있는 객체(여기에선 cout)를 좌항에 대해 피연산자로 요구하고 있다.
- 즉, 'cout << x'라는 표현 자체가 iostream에 있는 객체로 해석될 수 있다.
<< 연산자 오버로딩
//time.h
#include <iostream>
#ifndef TIMEH
#define TIMEH
class Time {
private:
int hours, mins;
public:
Time();
Time(int, int);
~Time();
friend std::ostream& operator<<(std::ostream&, Time&);
};
#endif // !TIMEH
//func.cpp
#include "time.h"
Time::Time() {
hours = mins = 0;
}
Time::Time(int h, int m) {
hours = h;
mins = m;
}
Time::~Time() {
}
//<< 연산자는 좌항의 값으로 ostream의 객체를 요구하고 있기 때문에, return형이 os의 참조(ostream&)이다.
std::ostream& operator<<(std::ostream& os, Time& t) {
os << t.hours << "시간 " << t.mins << "분";
return os;
}
//main.cpp
#include <iostream>
#include "time.h"
using namespace std;
int main() {
Time t1(3, 45);
cout << t1;
return 0;
}