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

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

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

假设您的意思是 operator<< 代表 std::ostream,您可以将 Borac 转换为 Karta 以使用基础 class 运算符(然后附加任何特定的对于 Borac)。否则,如果您的运营商是 class 会员,您可以使用 .

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

See it online

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

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

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

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;