请考虑以下代码段:
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";
}
};
Run Code Online (Sandbox Code Playgroud)
有没有办法改变Print的ObjectInterface,以标准的" std::ostream& operator<<"输出型?我不能让它发挥作用.
编辑:我基本上想弄清楚我是否可以friend合作virtual.
小智 6
你需要一个免费的功能:
ostream & operator << ( ostream & os, const ObjectInterface & oi ) {
oi.Print( os );
return os;
}
Run Code Online (Sandbox Code Playgroud)