【问题标题】:Return type ostream for derived class派生类的返回类型 ostream
【发布时间】:2018-10-10 05:19:51
【问题描述】:

通过继承,我试图在我的基类中创建一个重载的输出运算符,该运算符调用正确派生类中的输出函数,以根据对象类型打印正确的数据。

如何返回一个可以发送到重载输出运算符的输出,以便仅使用cout << object << endl; 输出对象

例如:

ostream & operator<< (ostream &out, const person &rhs){
    out << rhs.print_data();
    return out;
}

ostream student::print_data(){
    ostream out;
    out << data;
    return out;
}

ostream faculty::print_data(){
    ostream out;
    out << data;
    return out;
}

编辑:我想弄清楚是否需要在打印函数中返回类型 ostreamostream &amp;

【问题讨论】:

  • 是的,谢谢@UlrichEckhardt

标签: c++ inheritance operators ostream


【解决方案1】:

流不能被复制,所以如果你想返回(或作为参数传递)它必须通过引用来完成。而且您不能返回对局部变量的引用(因为它们会超出范围并“消失”)。

此外,基本的std::ostream 对象没有意义创建其实例。

简单的解决方案:将流作为参数(当然是通过引用)传递给函数:

ostream& operator<< (ostream &out, const person &rhs){
    return rhs.print_data(out);  // No need for any output here
}

ostream& student::print_data(ostream& out){
    return out << data;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-29
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多