我有两个班级,有两个 global friend oparator<<
。
class A {
friend std::ostream& operator<<(std::ostream& o, const A &a);
};
class B: public A {
friend std::ostream& operator<<(std::ostream& o, const B &b);
};
如果我这样使用它,一切正常,B
运算符的版本被调用:
B b;
std::cout << b;
但是,如果我使用多态性,则会A
调用该版本,尽管动态类型是B
:
A* b = new B();
std::cout << *b;
一种解决方案是铸造:
std::cout << static_cast<B&>(*b);
但是有没有更简单或更优雅的解决方案呢?