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

问题描述 投票:0回答:1

我有一个基类Karta和派生类Borac。在Karta类中,我重载了运算符<<,但在派生类(Borac)中,我想调用基类的函数operator<<(),然后在最终输出中添加更多的文本。

c++ class object inheritance operator-overloading
1个回答
0
投票

要调用一个特定的重载,你可以将相应的参数投向该特定重载所期望的类型。

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;

0
投票

为了调用一个基类函数,在函数前指定基类名称,类似于命名空间语法。

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

0
投票

假设你的意思是 operator<< 对于 std::ostream你可以投 BoracKarta 使用基类操作符(然后附加任何特定的东西给 Borac). 否则,如果你的操作符是类成员,你可以使用 另一个答案.

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

在线观看

© www.soinside.com 2019 - 2024. All rights reserved.