V
Victor
Anyone knows how to write a virtual function for operator<< ?
I have a base class and some public derived class from it.
For the derived class, I hope they can use << to output their
different data. What's more, I want the base class pointers
can access the derived ones and then their corresponding
operator <<. For example:
class base {
// virtual and friend can't be put together, so the following
// code won't work.
virtual friend ostream& operator<< (ostream& os, const base& b);
};
class derived1 : public base
{
virtual friend ostream& operator<< (ostream& os, const base& d1);
};
class derived2 : public base
{
virtual friend ostream& operator<< (ostream& os, const base& d2);
};
I hope they can work like:
base *pb;
derived1 d1;
derived2 d2;
cout<<d1<<"\t"<<d2<<endl; // use their corresponding defination
pb = &d1; // point to class derived1
cout<<*pb<<endl; // use the operator<< defined in class derived1
pb = &d2; // point to class derived2
cout<<*pb<<endl; // use the operator<< defined in class derived2
How could I implement the operator overloading then? thanks.
I have a base class and some public derived class from it.
For the derived class, I hope they can use << to output their
different data. What's more, I want the base class pointers
can access the derived ones and then their corresponding
operator <<. For example:
class base {
// virtual and friend can't be put together, so the following
// code won't work.
virtual friend ostream& operator<< (ostream& os, const base& b);
};
class derived1 : public base
{
virtual friend ostream& operator<< (ostream& os, const base& d1);
};
class derived2 : public base
{
virtual friend ostream& operator<< (ostream& os, const base& d2);
};
I hope they can work like:
base *pb;
derived1 d1;
derived2 d2;
cout<<d1<<"\t"<<d2<<endl; // use their corresponding defination
pb = &d1; // point to class derived1
cout<<*pb<<endl; // use the operator<< defined in class derived1
pb = &d2; // point to class derived2
cout<<*pb<<endl; // use the operator<< defined in class derived2
How could I implement the operator overloading then? thanks.