C++, How do I call a Base classes' overloaded extraction operator in a derived class?
所以这是我的一个大作业的一小部分,我只是不确定它的语法。
我有一个名为
(我使用的是名称空间
我给
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; |
我还有一个
如何在
我需要它在
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; } |
。