2

考虑以下代码段:

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

有什么办法可以更改PrintObjectInterface标准的“ std::ostream& operator<<”输出类型?我不能让它工作。

编辑:我基本上是想弄清楚我是否可以friend使用virtual.

4

1 回答 1

6

您需要一个免费功能:

ostream & operator << ( ostream & os, const ObjectInterface & oi ) {
    oi.Print( os );
    return os;
}
于 2009-04-11T20:14:08.817 回答