C ++,如何在派生类中调用Base类的重载提取运算符?

时间:2011-12-08 09:12:44

标签: c++ inheritance override overloading

所以这只是我所做的大型作业的一小部分,我只是不确定这个的语法。

我有一个名为Vehicle的基类,其中包含以下成员:int fuelAmtint fuelUsage

(我正在使用名称空间std

我以这种方式重载<<运算符:

ostream& operator<<(ostream& osObject, const Vehicle& myVehicle)
{
    cout << "Fuel Usage Rate: " << myVehicle.fuelUsage << endl
         << "Fuel Amount:     " << myVehicle.fuelAmt << endl;

    return osObject;
}

然后我这样称呼它:

cout << Vehicle;

结果是(示例):

Fuel Usage Rate: 10;
Fuel Amount: 50;

我还有一个Airplane类派生自Vehicle类,它引入了一个新成员:int numEngines

如何重载<<类中的Airplane运算符,以便它首先调用“Vehicle overloaded运算符结果”,然后是我告诉<<的结果运算符从派生类打印...所以,这就是我的意思:

我需要它在Airplane类中以这样的方式运行:

ostream& operator<<(ostream& osObject, const Airplane& myAirplane)
{
        //First print the Fuel Usage rate and Fuel amount by calling
        //the Base class overloaded << function

         //then
        cout << "Number of Engines: " << myAirplane.numEngines << endl;

    return osObject;
}

如何在此派生类中触发输出其成员值的基类执行?

是否更改标题?像这样:

ostream& operator<<(ostream& osObject, const Airplane& myAirplane): operator<<Vehicle

3 个答案:

答案 0 :(得分:16)

以下内容如何:

ostream& operator<<(ostream& osObject, const Airplane& myAirplane)
{
    osObject << static_cast<const Vehicle &>(myAirplane);
    osObject << "Number of Engines: " << myAirplane.numEngines << endl;

    return osObject;
}

答案 1 :(得分:16)

由于运营商&lt;&lt;是一个非成员函数,你不能将它声明为虚拟,理想情况下你想要它。所以你做了以下

class Base
{
public:
    virtual std::ostream& output(std::ostream& out) const
    {
        return out << "Base";
    }
    virtual ~Base() {} //Let's not forget to have destructor virtual
};

class Derived : public Base
{
public:
    virtual std::ostream& output(std::ostream& out) const
    {
        Base::output(out); //<------------------------
        return out << "DerivedPart";
    }
    virtual ~Derived() {} //Let's not forget to have destructor virtual
};

最后,让运营商&lt;&lt;仅适用于基类,虚拟调度将发挥其魔力

std::ostream& operator << (std::ostream& out, const Base& b) 
{
    return b.output(out);
}

答案 2 :(得分:1)

ostream& operator<<(ostream& osObject, const Airplane& myAirplane)
{
     //First print the Fuel Usage rate and Fuel amount by calling
     //the Base class overloaded << function
     cout << (Vehicle& ) myAirplane;

     //then
     cout << "Number of Engines: " << myAirplane.numEngines << endl;

     return osObject;
}