C++
iostream operator function overloading
GOD03219
2018. 9. 20. 08:28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 |
#include<iostream>
#include<string>
using namespace std;
class A {
int a;
public:A(int num = 0) :a(num) {
}
friend ostream& operator <<(ostream&out, A&aa);
friend istream& operator >>(istream &in, A&aa);
};
ostream& operator <<(ostream & hi, A&aa) {
hi << aa.a<<endl; // <<는 출력연산자
return hi;
}
istream & operator >> (istream &loo, A&aa)
{
loo>> aa.a; // >>는 입력연산자
return loo;
}
void main() {
A aa(100);
A bb;
cout << aa << bb; // 100 0 출력
cin >> aa >> bb ; // aa.a 입력, bb.a 입력
cout << aa << bb; // 입력한 값대로 나옴
}
|
cs |
입출력 스트림은 std안에 있기 때문에 멤버함수로 오버로딩할 수 없다.
외부함수로 빼고 그 외부함수를 friend로 선언해야 한다.
어느 클래스 안에 있을 수 없기 때문에 return *this 를 할 수 없다.