class that behaves as ostream

I need to code a class that behaves as a cout (or is used instead of a cout). The class is constructed by getting a reference to a cout - so it would be

ClassName nam(&cout);

and then to output a string or something
nam << "output"; //prints 'output'
there are more stuff to do but I can figure that out, its just that I never programmed something similar and I cant find an example of what I am looking for...

Thanks
I am not so experienced with c++ and I forgot some stuff...
Anyway I realized that I should be overloading the << operator for the class, but the problem is that in the main there can be either

nam << string
//or
nam << int //or double

is there a way to overload for all types at once instead of overloading for each var type separately?
If you're making a logger, spend some time evaluating the multitude of logger libraries available for C++.

That said, it's sufficient to do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class ClassName
{
    std::ostream* p;
 public:
    ClassName(std::ostream* p) : p(p) {}
    template<typename T>
    ClassName& operator<<(const T& t) {
        (*p) << t;
        // now consider error handling
        return *this;
    }
};

int main()
{
    ClassName nam(&std::cout);
    std::string s = " test";
    nam << "output\n" << 7 << s << '\n';
}
Last edited on
Ok, this works but...

I guess I should given more info - as I am a beginner in c++ and this is a school assignment, we did not use templates. Below is the main we got, and we are supposed to code a SpyOutput class that will count the number of chars that passed thru it, and their ASCII sum. My problem is that we were not given an example where a cout (ostream) is passed to a constructor. Also I am a bit rusty with all of this...

Oh and I should be overloading the << operator, so can someone just show me the prototype? The logic of programming is simple for me, but its the syntax I have trouble with...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "SpyOutput.h"
#define endl   '\n'
#include<iostream>
using namespace std;

int main()
{
	double d1 = 12.3;
	int i1 = 45;
	SpyOutput spy();

	spy << "abca" << endl;
	spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl;
	cout << "count=" << spy.getCount() << endl;
	cout << "Check Sum=" << spy.getCheckSum() << endl;
}
Topic archived. No new replies allowed.