Help with Deque - ostream_iterator
Mar 26, 2011 at 12:58pm UTC
Hey guys need a little help with the STL and ostream_iterator.
I've commented the code which isn't doing what I think it should do.
I tried using virtual in the base class for the operator but that just led to errors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include <iostream>
#include <iterator>
#include <deque>
using std::cin;
using std::cout;
using std::endl;
using std::ostream;
class Base{
public :
Base(int foo = 5): test(foo){}
friend ostream& operator <<(ostream &stream, const Base &obj){
stream << obj.test << endl;
return stream;
}
int return_test()const {return test;}
private :
int test;
};
class Dervied : public Base{
public :
Dervied(): Base(5){cha = 'a' ;}
friend ostream& operator <<(ostream &stream, const Dervied &obj){
stream << obj.return_test() << " " << obj.cha;
return stream;
}
private :
char cha;
};
class Dervied2 : public Base{
public :
Dervied2(): Base(5){cha = 'z' ;}
friend ostream& operator <<(ostream &stream, const Dervied2 &obj){
stream << obj.return_test() << " " << obj.cha;
return stream;
}
private :
char cha;
};
int main(){
std::deque<Base> test;
Dervied one;
Dervied2 two;
test.push_back(one);
test.push_back(two);
// Need this to use Dervied and Dervied2 operator<<
std::copy(test.begin(),test.end(),std::ostream_iterator<Base>(cout, " " ));
cin.get();
return 0;
}
So what I want to happen is that it uses the Dervied and Dervied2 operator<<'s to show what is in the object yet it just uses the Base class instead.
Thanks guys.
Mar 26, 2011 at 2:15pm UTC
It doesn't work that way. I'd suggest you to write just one ostream<< operator for the base class, that uses a protected virtual method printOn(ostream), and you override the printOn method in the derived class.
Mar 26, 2011 at 11:59pm UTC
Thank you hanst99 for the help worked perfectly.
Topic archived. No new replies allowed.