C++ Passing ostream as parameter

别说谁变了你拦得住时间么 提交于 2019-12-09 10:27:05

问题


I'm working on a homework project for a virtual rolodex that has called for a main class, a rolodex class, and a card class. To output the contents of all of the "cards" to the console, the assignment says that main() should call a show(...) function in the rolodex class, passing it an ostream and show(...) then iterates over the cards, calling each of their showCard() functions. The actual showing is done by the card objects' showCard() function, showing on the provided ostream.

What I don't understand is why an ostream would/should be passed anywhere. Seems like the assignment is calling for something like this:

main() {
   Rolodex myRolodex; 
   ostream myStream; 
   myRolodex.show(myStream); 
}

void Rolodex::show(ostream& theStream) {
   //for each card 'i' in the Rolodex...
   myCard[i].show(theStream);
}

void Card::show(ostream& theStream) {
   theStream << "output some stuff" << endl;
}

instead of something like this:

main() {
   Rolodex myRolodex;  
   myRolodex.show(); //no ostream passed 
}

void Rolodex::show() {
   //for each card 'i' in the Rolodex...
   myCard[i].show();//no ostream passed
}

void Card::show() {
   cout << "output some stuff" << endl;
}

Am I either misunderstanding the use of ostream as a parameter or missing some other obvious reason to pass an ostream down the stream like that?


回答1:


What I don't understand is why an ostream would/should be passed anywhere.

This is often used for things like testing. Say you want console output normally, so you'd pass around a reference to std::cout. But sometimes you want to do testing, e.g. unit or acceptance testing, and you want to store the output in memory for that. You could use std::stringstream for this, and the function you're working with is none the wiser.

That's one specific case -- but in general any place where you'd want to change where the data source or sink could be coming from / going to, you can do that by passing a stream around.

For example, the following would print your rolodex to the console:

int main()
{
    Rolodex myRolodex;
    myRolodex.show(std::cout);
}

... but if tomorrow you wanted to write to a file instead, you can do that without affecting the code inside Rolodex at all:

int main()
{
    Rolodex myRolodex;
    std::ofstream file("This\\Is\\The\\Path\\To\\The\\File.txt");
    myRolodex.show(file); // Outputs the result to the file,
                          // rather than to the console.
}



回答2:


I would just overload the << operator:

class Card{
public:
    friend ostream& operator<<(ostream& os, const Card& s);
};

ostream& operator<<(ostream& os, const Card& s){
    os << "Print stuff";
    return os;
}

And you could overload in the Rolodex as well to just iterate over the cards.



来源:https://stackoverflow.com/questions/5507924/c-passing-ostream-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!