简体   繁体   English

基类中的重载输出运算符

[英]Overloaded output operator in base class

I have a number of classes that represent various computer components, each of which have an overloaded << operator declared as follows: 我有许多代表各种计算机组件的类,每个类都有一个重载的<<运算符,声明如下:

friend ostream& operator << (ostream& os, const MotherBoard& mb);

Each returns an ostream object with a unique stream describing that component, some of which are composed of other components. 每个返回一个ostream对象,该对象具有描述该组件的唯一流,其中一些由其他组件组成。 I decided to create a base class called Component in order to generate a unique id as well as some other functions that all the components will publicly derive. 我决定创建一个名为Component的基类,以生成唯一的ID以及所有组件将公开派生的其他一些功能。 Of course, the overloaded << operator doesn't work with pointers to Component objects. 当然,重载的<<操作符不适用于指向Component对象的指针。

I was wondering how I would effect something like a pure virtual function that will be overwritten by each derived class's << operator so I could do something like: 我想知道如何影响像纯虚函数那样的东西,该函数会被每个派生类的<<运算符覆盖,因此我可以执行以下操作:

Component* mobo = new MotherBoard();

cout << *mobo << endl;

delete mobo;

Also related to: overloading << operators and inherited classes 还与以下内容有关: 重载<<运算符和继承的类

Maybe something like this: 也许是这样的:

#include <iostream>

class Component 
{
public:
    // Constructor, destructor and other stuff

    virtual std::ostream &output(std::ostream &os) const
        { os << "Generic component\n"; return os; }
};

class MotherBoard : public Component
{
public:
    // Constructor, destructor and other stuff

    virtual std::ostream &output(std::ostream &os) const
        { os << "Motherboard\n"; 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM