Istream and ostream in inheritance
I have two classes:
class a{
friend istream &operator>> (istream&in, a&ob) { }
friend ostream &operator<< (ostream&out, const a&ob) { }
}
class b:public a{
friend istream &operator>> (istream&in, b&ob) { }
friend ostream &operator<< (ostream&out, const b&ob) { }
}
The class works great. I can read and write objects of type a. Class b inherits everything from class a and adds some new data. In my istream and ostream class b statements, is there a way to read and write common fields using class a I / O statements? Thank.
+3
source to share
2 answers
Keep extractor and insert overloading for the base class, and defer the actual operation to the virtual member function:
istream& operator>>(istream& in, a& ob)
{
ob.read(in);
return in;
}
ostream& operator<<(ostream& out, const a& ob)
{
ob.write(out);
return out;
}
The power for b
can simply call the base class overload:
class b : public a {
public:
void read(std::istream& is) {
a::read(is);
// read into derived class
}
void write(std::ostream& os) {
a::write(os);
// write out derived class
}
};
+1
source to share