我有两个类(class):父亲和儿子。儿子继承了父亲。
两者都在重载 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"
};
有没有办法,我可以从儿子那里调用父亲的“<<”?
我希望 Son 最终会打印:“父子”
最佳答案
你可以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;
}
};
关于c++ - 使用父类的重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33867762/