J's Study log

[C++] Operation Overloading - How 'std' works 본문

Computer Language/C++

[C++] Operation Overloading - How 'std' works

정우섭 2020. 5. 25. 22:44

Now let's figure out the basic idea of 'cout, cin, endl'.

 

After studying about operation overloading, now you are ready to learn how 'std' works.

 

Please, just read the following code.

 

#include <iostream>
namespace mystd;
{
	using namespace std;
    
    class ostream
    {
    public:
    	void operator<< (char *str)
        {
        	printf("%s", str);
        }
        void operator<< (char str)
        {
        	printf("%c", str);
        }
        void operator<< (int num)
        {
        	printf("%d", num);
        }
        void operator<< (double e)
        {
        	printf("%g", e);
        }
        void operator<< (ostream &(*fp)(ostream &ostm))
        {
        	fp(*this);
        }
    };
    
    ostream &endl(ostream &ostm)
    {
    	ostm<<'\n';
        fflush(stdout);
        return ostm;
    }
    
    ostream cout;
}

int main(void)
{
	using mystd::cout;
    using mystd::endl;
    
    cout<<"Simple String";
    cout<<endl;
    cout<<3.14;
    cout<<endl;
    cout<<123;
    endl(cout);
    return 0;
}

 

Of course this code is not the real 'cout, cin, endl' itself.

 

It's just a simple imitation of them.

 

Each 'cout' in line 46, 48, 50 are same as

 

cout.operator<<("Simple String");	//same as line 46
cout.operator<<(3.14);				//same as line 48
cout.operator<<(123);				//same as line 50

 

And they are from namespace 'mystd'.

 

Also line 47, 49 both are same as

 

cout.operator<<(endl);

 

 

 

 

 

 

 

 

 

[참고자료]

- 윤성우의 열혈 C++ 프로그래밍

'Computer Language > C++' 카테고리의 다른 글

[C++] Shallow Copy & Deep Copy  (0) 2020.06.02
[C++] Operation Overloading - Assignment Operator  (0) 2020.05.30
[C++] Operator Overloading 2  (0) 2020.05.07
[C++] Operator Overloading 1  (0) 2020.05.02
[C++] Default Value of the Parameter  (0) 2020.05.02
Comments