如何调用继承的重载运算符<<并在派生类的输出中添加更多文本?

How can i call inherited overloaded operator << and add more text in output in derived class?

本文关键字:lt 输出 派生 添加 文本 继承 重载 运算符 何调用 调用      更新时间:2023-10-16

我有基类Karta和派生类Borac。在类 Karta 中,我重载了运算符 <<,但在派生类 (Borac( 中,我想为基类调用函数运算符<<((,然后在最终输出中添加更多文本。 怎么做?

若要调用特定重载,可以将相应的参数强制转换为该特定重载所需的类型:

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;
}

输出:

Base;Derived;

为了调用基类函数,请指定附加到函数前面的基类名称,类似于命名空间语法:

Type Borac::operator<<() {
Karta::operator<<(); // calls operator<<() of the Karta class on this
// Here goes any additional code
}

假设你的意思是operator<<std::ostream,你可以Borac强制转换为Karta以使用基类运算符(然后附加任何特定于Borac的内容(。否则,如果您的运算符是类成员,则可以使用其他答案。

std::ostream& operator<< (std::ostream& os, const Borac& b) {
os << dynamic_cast<const Karta&>(b);
os << "Additional part for Borac";
return os;
}

在线查看