我有两个班:父亲和儿子。儿子延伸父亲。
两者都在重载ostream运算符。
class Father {
public:
friend ostream& operator<<(ostream& os, Father& v); //prints "father"
};
class Son : public Father {
public:
friend ostream& operator<<(ostream& os, Son& v); // prints "son"
};
有没有办法,从儿子我可以称为父亲&#34;&lt;&lt;&#34; ?
我希望儿子最终会打印出来:&#34;父亲的儿子&#34;
答案 0 :(得分:2)
您可static_cast
Son&
到Father&
:
class Son : public Father {
public:
friend std::ostream& operator<<(std::ostream& os, Son& v) {
os << static_cast<Father&>(v);
os << "son";
return os;
}
};
答案 1 :(得分:1)
您可以使用虚拟方法覆盖。
class Father
{
public:
virtual std::ostream& operator<<(std::ostream& os)
{
os << "father";
return os;
}
};
class Son : public Father
{
public:
std::ostream& operator<<(std::ostream& os) override
{
Father::operator<<(os);
os << " son";
return os;
}
};
但是,正如TartanLlama所说,这会切换运算符的参数,所以你最终会像这样使用它:
Son s;
s << std::cout;