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

C++, How do I call a Base classes' overloaded extraction operator in a derived class?

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

我有一个名为Vehicle的基类,它有这些成员:int fuelAmtint fuelUsage

(我使用的是名称空间std)

我给<<操作员超载了:

1
2
3
4
5
6
7
ostream& operator<<(ostream& osObject, const Vehicle& myVehicle)
{
    cout <<"Fuel Usage Rate:" << myVehicle.fuelUsage << endl
         <<"Fuel Amount:    " << myVehicle.fuelAmt << endl;

    return osObject;
}

然后我这样称呼它:

1
cout << Vehicle;

结果是(示例):

1
2
Fuel Usage Rate: 10;
Fuel Amount: 50;

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

如何在Airplane类中重载<<运算符,使其首先调用"车辆重载运算符结果",然后调用我告诉<<运算符从派生类打印的任何结果…我的意思是:

我需要它在Airplane类中这样工作:

1
2
3
4
5
6
7
8
9
10
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;
}

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

是不是有点像改变标题?这样地:

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


由于运算符<<是非成员函数,因此不能将其声明为虚函数,这是理想情况下所需的。所以你要做以下的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
};

最后,让操作符<<仅用于基类,虚拟调度将发挥其魔力。

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

下面怎么样?

1
2
3
4
5
6
7
ostream& operator<<(ostream& osObject, const Airplane& myAirplane)
{
    osObject << static_cast<const Vehicle &>(myAirplane);
    osObject <<"Number of Engines:" << myAirplane.numEngines << endl;

    return osObject;
}


1
2
3
4
5
6
7
8
9
10
11
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;
}