试图将ostream传递给函数并计算结果ostream

Trying to pass ostream to function and cout the resulting ostream

本文关键字:ostream 函数 计算 结果      更新时间:2023-10-16

需求是创建一个流,将其传递给第二个函数进行修改(必须以这种方式传递,因为输出需要访问单独类的私有数据成员)。然后输出修改后的流。它按原样编译,但只返回MyStream的地址,我需要它来返回流。

/* Prints the details of the media collection. */
void MediaCollection::PrintMediaDetails() const{
    ostream MyStream(NULL);
    for(int i = 0; i < CurrentMCSize; i++){
        TheCollection[i]->PrintMedia(MyStream);
        cout << i + 1 <<" : "<<&MyStream;
    }
}
/*Takes Stream and and returns data members*/
void Media::PrintMedia(ostream & Out) const{
    Out<<Title<<" "<<Artist<<" "<<&RunningTime<<endl;
}

它正在打印MyStream的地址,因为你告诉它

改变
<<&MyStream;

<<MyStream;

但是ostream MyStream(NULL)没有传递一个streambuf

就没有任何意义

cpp-progger建议使用std::ostringstream。像这样定义一个

ostringstream MyStream;

并使用

打印内容
cout << i + 1 <<" : "<< MyStream.str();