基类中重载的输出运算符

时间:2012-02-10 12:58:34

标签: c++

我有许多代表各种计算机组件的类,每个类都有一个重载的<<运算符,声明如下:

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

每个返回一个ostream对象,该对象具有描述该组件的唯一流,其中一些组件由其他组件组成。我决定创建一个名为Component的基类,以便生成唯一的id以及所有组件将公开派生的一些其他函数。当然,重载的<<运算符不适用于指向Component个对象的指针。

我想知道如何影响像每个派生类的<<运算符覆盖的纯虚函数,所以我可以做类似的事情:

Component* mobo = new MotherBoard();

cout << *mobo << endl;

delete mobo;

还与:overloading << operators and inherited classes

有关

1 个答案:

答案 0 :(得分:5)

也许是这样的:

#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;
}
相关问题