C ++ Passing ostream as a parameter

I am working on a home project for a virtual rodeodex that called for the main class, rolodex class and map class. To display the contents of all the "cards" to the console, the destination indicates that main () should call the show (...) function in the rolodex class, passing it ostream and show (...), then iterating over the cards, calling each of its showCard () functions. The actual mapping is performed by the showCard () function of the map object displayed on the provided stream.

I do not understand why ostream should / should be passed anywhere. The job seems to call 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 the following:

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

ostream , - , ?

+5
2

, ostream / .

, . , , , std::cout. , . , . std::stringstream , , , .

- , , , .

, rolodex :

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

... , , Rolodex:

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

<<:

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

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

Rolodex, .

+2

All Articles