Help Needed in Overloading operator<<

Joined
Oct 2, 2010
Messages
2
Reaction score
0
So, I am new here, but I need some help. I am looking to overload 'operator<<' so I can modify the behavior of 'std::cout' in 'main()'. This is really just bare-bones experiment that will be built on for some other things. What I have so far is this:

#include <iostream>
#include <cstdio>

using namespace std;

ostream& operator<< (ostream& os, const char* str) {
puts ("Hello World");
return os;
}

main ()
{ cout << "hello" << i << endl; }

What this setup allows me to do is override the 'operator<<' function signature for a string constant. When I get into my implementation of the operator, I ignore the string that arrives through the parameter 'char* str' and print my own string "Hello World" to 'stdio' using the function 'puts' which is also tied to stdio.

While this implementation works, I am not satisfied with it. I want to create my own ostream, say "mycout" which is tied to 'stdout' and use this new c++ stream rather than relying on 'puts'. Unfortunately this is where I get in over my head. iostreams are not an area of c++ that I have done much work in. I can't seem to find the C++ magic that will allow me to define the stream "mycout" and tie it to stdio. Can this be done? Can someone offer me some advice on this? It would be greatly appreciated.

I know that my desire to do this with iostreams rather than puts might be a bit arbitrary, but in addition to getting the job done, I am looking to get a better understanding of iostreams.

Oh one more thing... where does one find the implementation of 'cout'. How does it implement its 'operator<<'
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top