c++ - 基类中的重载输出运算符

标签 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

最佳答案

也许是这样的:

#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;
}

关于c++ - 基类中的重载输出运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228173/

相关文章:

c++ - 在析构函数中调用 "compiler is out of heap space"运算符时出现编译器错误 `delete`

c++ - 如何将 DWORD 转换为 wstring?

c++ - 返回字符串中模式的所有非重叠匹配项

C++ 标准库 - 我应该什么时候使用它,什么时候不应该使用它?

c++ - 在类构造函数中初始化引用变量

python - "No module named ' _<module> '"导入带有嵌入式 Python 的 SWIG 模块时

c++ - 如何识别从不同子类覆盖的 vector 类?

c++ - 串口传输错误如何解决?

c++ - 对角反射矩阵

c++ - 是否有可能在没有安装opencv的linux中运行opencv项目