在C ++中继承类的流

时间:2015-04-16 14:17:24

标签: c++ inheritance stream

我有两节课: 父类:车辆

class Vehicle {
    private:
        string manufacturer;
        int cylinder;
        Person owner;
    public:
        Vehicle();
        Vehicle(const Vehicle& theObject);
        friend istream& operator >>(istream& inStream, Vehicle& object);
        friend ostream& operator <<(ostream& outStream, const Vehicle& object);
};

和孩子班:卡车 我重载了operator<<operator>>,以便我可以将coutcin与我的班级卡车一起使用。以下是我对这两个运算符的定义:

class Truck : public Vehicle {
    private:
        double loadCapacity;
        int towingCapacity;
    public:
        Truck();
        Truck(const Truck& object);
        friend istream& operator >>(istream& inStream, Truck& object);
        friend ostream& operator <<(ostream& outStream, const Truck& object);
};

istream& operator >>(istream& inStream, Truck& object) {
    cout << endl << "Insert truck: "; inStream >> object;
    cout << "Insert load capacity: "; inStream >> object.loadCapacity;
    cout << "Insert towing capacity: "; inStream >> object.towingCapacity;
    return inStream;
}

ostream& operator <<(ostream& outStream, const Truck& object) {
    outStream << object;
    outStream << endl << "Load capacity: " << object.loadCapacity;
    outStream << endl << "Towing capacity: " << object.towingCapacity;
    return outStream;
}

当我尝试使用

Truck object;
cin >> object;
cout << object

我觉得它没有用。谁能解释为什么? 谢谢

1 个答案:

答案 0 :(得分:1)

inStream >> objectoutStream << object都是递归调用,因为object的静态类型是Truck,而不是Vehicle。使用print覆盖的虚拟getTruck方法。在插件中调用object.print(outStream),在提取器中调用object.get(inStream),以通过继承实现多态I / O:

class Vehicle {
private:
    string manufacturer;
    int cylinder;
    Person owner;
public:
    Vehicle();
    Vehicle(const Vehicle& theObject);
    virtual void print(std::ostream& os) const {
        os << manufacturer << cylinder << owner;
    }
    virtual void get(std::istream& is) {
        is >> manufacturer >> cylinder >> owner;
    }
};

class Truck : public Vehicle {
private:
    double loadCapacity;
    int towingCapacity;
public:
    Truck();
    Truck(const Truck& object);
    void print(std::ostream& os) const {
        Vehicle::print(os);
        os << loadCapacity << towingCapacity;
    }
    void get(std::istream& is) {
        Vehicle::get(is);
        is >> loadCapacity >> towingCapacity;
    }
};

std::istream& operator>>(std::istream& inStream, Vehicle& object) {
    object.get(inStream);
    return inStream;
}

std::ostream& operator<<(std::ostream& outStream, const Vehicle& object) {
    object.print(outStream);
    return outStream;
}