nakka soft world !

cout & ostream 본문

프로그래밍언어/C++

cout & ostream

nakka 2017. 3. 19. 01:44
728x90
cout & ostream능


1. cout의 원리

int main()

{

int n= 10;

double d = 3.4;


cout << n;  // cout.operator<<(n) => cout.operator<<(int )

cout << d; // cout.operator<<(double ), 연산자 오버로딩.


cout.operator<<(n);

cout.operator<<(d);

}


2. cout 업그레이드

#include <cstdio>


namespace std

{

clase ostream  // basic_ostream<> 인터넷으로 검색하면 cout의 구현부 확인 가능

{

public:

//void operator<<(int n) { printf("%d", n); }

osteram& operator<<(int n) { printf("%d", n); return *this; }

//void operator<<(double v) { printf("%f", d); }

ostream& operator<<(double v) { printf("%f", d); return *this; }

ostream& operator<<(char c) { printf("%c", c); return *this; }

};

ostream cout;

}


int main()

{

cout << 3; // cout.operatoe<<(int )

cout << 3.4; // cout.operatoe<<(double )


cout << 3 << 3; // return값으로 cout이 나오는 형태임.


cout << 3 << 3 << '\n'; // 개행.

}


3. endl의 원리

namespace std

{

clase ostream

{

public:

osteram& operator<<(int n) { printf("%d", n); return *this; }

ostream& operator<<(double v) { printf("%f", d); return *this; }

ostream& operator<<(char c) { printf("%c", c); return *this; }


ostream& operator<<( ostream&(*r)(ostream&)) { f(*this); return *this }

};

ostream cout;


ostream& endl(ostream& os)  // 조정자 함수.

{

os << '\n';

return os;

}

}


int main()

{

//cout << endl; // 개행, cour.operator<<(endl) => cout.operator<<(함수포인터)

endl(cout); // 위와 동일 표현

}


4. 사용자 정의 타입과 cout

class Point

{

private:

int x, y;

public:

Point(int a = 0, int b = 0; : x(a), y(b) {}

friend ostream& operator<<(ostream& os, const Point& pt);

};

ostream& operator<<(ostream& os, const Point& pt) // 추출 연산자 재정의

{

os << pt. << ", " << pt.y;

return os;

}


int main()

{

Point pt(1, 2);

cout << pt; // 1. cout.operator<<(pt) -=> cout.operator<<(Point)

// 2. operator<<(cout, pt) -> operator<<(ostream, Point)


}

728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

함수 객체(function object, fonctor)  (0) 2017.03.19
증가/감소 연산자 재정의  (0) 2017.03.19
연산자 재정의 개념  (0) 2017.03.19
this  (0) 2017.03.19
상수 멤버 함수 (const member function)  (0) 2017.03.19
Comments