이번에는 C++에서 흔히 사용하는 std::cout을 만들어보자
class ostream
{
public:
const ostream& Print(const int i) const
{
printf("%i", i);
return *this;
}
const ostream& Print(const float f) const
{
printf("%f", f);
return *this;
}
const ostream& Print(const char* s) const
{
printf("%s", s);
return *this;
}
};
이런식으로 정의하게 되면
ostream cout;
int main()
{
int i = 3;
float f = 4.1f;
cout.Print(i).Print(f).Print("Hello");
}
이런식으로 사용할 수 있다. 하지만, 우리가 사용하는 그런 Print 명령어가 아니다. 이번에도 operator를 사용해서 비슷하게 만들어보자
class ostream
{
public:
const ostream& operator<<(const int i) const
{
printf("%i", i);
return *this;
}
const ostream& operator<<(const float f) const
{
printf("%f", f);
return *this;
}
const ostream& operator<<(const char* s) const
{
printf("%s", s);
return *this;
}
}
C++에서는 print대신 << 을 사용하고 있다. 이 연산자를 오버로딩 하여 재정의 해준다.
이렇게 만들면
ostream cout;
void main()
{
int i = 3;
float f = 4.1f;
cout << i << f << "hello";
}
이런식으로 사용이 가능하다.
하지만 개행으로 사용하던 endl이 없다. 뭔가 허전하다.
이 endl은 함수 포인터를 인자로 받아 사용한다.
void endl()
{
printf("\r\n");
}
class ostream
{
public:
const ostream& operator<<(const int i) const
{
printf("%i", i);
return *this;
}
const ostream& operator<<(const float f) const
{
printf("%f", f);
return *this;
}
const ostream& operator<<(const char* s) const
{
printf("%s", s);
return *this;
}
const ostream& operator<<(void(*manipulator)()) const
{
manipulator();
return *this;
}
};
이런식으로 endl을 정의 해주고 마지막으로 함수 포인터를 인자로 받아 함수를 실행하게 하게 되면
ostream cout;
void main()
{
int i = 3;
float f = 4.1f
cout << i << f << "hello" << endl;
}
이런식으로 우리가 사용하던 방식으로 사용이 가능하다.
'C++' 카테고리의 다른 글
6. STL Placement new (0) | 2022.12.17 |
---|---|
5. Operator Overloading03 operator new (2) | 2022.12.17 |
3. Operator Overloading Function (0) | 2022.12.14 |
2. Base From Member Idiom (0) | 2022.12.04 |
1. STL - Contaier and Iterator (0) | 2022.11.30 |