【问题标题】:Overloaded output operator in base class基类中重载的输出运算符
【发布时间】:2012-02-10 12:58:33
【问题描述】:

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

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

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

我想知道如何实现像纯虚函数这样的东西,它将被每个派生类的 &lt;&lt; 运算符覆盖,这样我就可以执行以下操作:

Component* mobo = new MotherBoard();

cout << *mobo << endl;

delete mobo;

还与:overloading << operators and inherited classes

【问题讨论】:

    标签: c++


    【解决方案1】:

    可能是这样的:

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

    【讨论】:

    • +1 我实际上已经看过几次了,这很有意义。但是,鉴于output 是公开的,operator&lt;&lt; 不必是朋友(也不应该)。另外,在过去我看到签名为:virtual std::ostream&amp; print( std::ostream&amp; out ) const;,因此如果手动调用它可以被链接:myobj.output( std::cout ) &lt;&lt; std::endl; 不过我不太喜欢这种语法。
    • @DavidRodríguez-dribeas 你说得对,不需要朋友声明,我猜只是习惯的力量。 :) 根据您的建议更新代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多