Istream和ostream继承

时间:2015-05-27 00:06:05

标签: c++

我有两个班级:

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) { }
}

A班很棒。我可以读写a类型的对象。类b继承了类a中的所有内容并添加了一些新数据。在我的istream和类b的ostream操作符中,是否有一种方法可以使用类a的输入/输出操作符来读取和写入公共字段?谢谢。

2 个答案:

答案 0 :(得分:2)

您可以通过将ob强制转换为超类的类型来重用运算符:

ostream &operator<< (ostream& out, const b& ob) {
   // Output the parts common to a and b
   out << static_cast<const a&>(ob);
   // Do additional things specific to b
   out << some_part_specific_to_b;
   return out;
}

答案 1 :(得分:1)

保持基类的提取器和插入器重载,并将实际操作推迟到虚拟成员函数:

istream& operator>>(istream& in, a& ob)
{
    ob.read(in);
    return in;
}

ostream& operator<<(ostream& out, const a& ob)
{
    ob.write(out);
    return out;
}

b的覆盖可以简单地调用基类重载:

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
    }
};