我有一个基类Karta和派生类Borac。在Karta类中,我重载了运算符<<,但在派生类(Borac)中,我想调用基类的函数operator<<(),然后在最终输出中添加更多的文本。
要调用一个特定的重载,你可以将相应的参数投向该特定重载所期望的类型。
struct Base {
};
struct Derived : public Base {
};
std::ostream &operator << (std::ostream & o, const struct Base &b) {
o << "Base;";
return o;
}
std::ostream &operator << (std::ostream & o, const struct Derived &d) {
o << dynamic_cast<const Base&>(d);
o << "Derived;";
return o;
}
int main() {
Derived d;
std::cout << d << std::endl;
}
Output:
Base;Derived;
为了调用一个基类函数,在函数前指定基类名称,类似于命名空间语法。
Type Borac::operator<<() {
Karta::operator<<(); // calls operator<<() of the Karta class on this
// Here goes any additional code
}