开发者

C++ Passing ostream as parameter

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" <开发者_StackOverflow社区;< 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?


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.
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜