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

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

评论
  • 陌路人
    陌路人 回复

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

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

    Assuming that you meant operator<< for std::ostream, you can cast Borac to Karta to use base class operator (and then append anything specific for Borac). Otherwise, if your operator is class member, you can use the other answer.

    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

  • 不要这样
    不要这样 回复

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

    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;