ABC虚拟OStream插入操作符

时间:2009-04-11 20:02:19

标签: c++ virtual

请考虑以下代码段:

struct ObjectInterface
{
    virtual ~ObjectInterface() {}
    virtual void Print(std::ostream& target) const = 0;
};

struct Foo : ObjectInterface
{
    virtual void Print(std::ostream& target) const
    {
        target << "Foo";
    }
};

struct Bar : ObjectInterface
{
    virtual void Print(std::ostream& target) const
    {
        target << "Bar";
    }
};

有没有办法将Print中的ObjectInterface更改为标准“std::ostream& operator<<” - 输出类型?我无法使它发挥作用。

编辑:我基本上是想弄清楚我是否可以friendvirtual合作。

1 个答案:

答案 0 :(得分:6)

您需要一个免费功能:

ostream & operator << ( ostream & os, const ObjectInterface & oi ) {
    oi.Print( os );
    return os;
}
相关问题