Overloaded output operator in base class
我有许多类表示各种计算机组件,每个类都有一个重载的
1 | friend ostream& operator << (ostream& os, const MotherBoard& mb); |
每一个都返回一个具有描述该组件的唯一流的Ostream对象,其中一些组件由其他组件组成。我决定创建一个名为
我想知道我将如何影响一个纯虚拟函数,它将被每个派生类的
1 2 3 4 5 | Component* mobo = new MotherBoard(); cout << *mobo << endl; delete mobo; |
号
还与以下内容相关:重载<<运算符和继承的类
可能是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <iostream> class Component { public: // Constructor, destructor and other stuff virtual std::ostream &output(std::ostream &os) const { os <<"Generic component "; return os; } }; class MotherBoard : public Component { public: // Constructor, destructor and other stuff virtual std::ostream &output(std::ostream &os) const { os <<"Motherboard "; return os; } }; std::ostream &operator<<(std::ostream &os, const Component &component) { return component.output(os); } int main() { MotherBoard mb; Component &component = mb; std::cout << component; } |