Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a print function that takes an ostream as an argument and writes to that stream

Im currently anwsering exercise questions concerning operator overloading in C++. I have a question:

Create a simple class containing an int and overload the operator+ as a member function. Also provide a print( ) member function that takes an ostream& as an argument and prints to that ostream&. Test your class to show that it works correctly.

I can create the class and write the operator+ function alright but I really dont understand the second part of the question. So far in my study of c++ I havent really come across ostream's and as such am not sure if its possible to explicitly create such a stream. I have tried using:

std::ostream o;

However this produces an error. Could someone please enlighten me on how I should create this function please?

like image 585
Bap Johnston Avatar asked Aug 24 '11 16:08

Bap Johnston


People also ask

What is Ostream function in C++?

The ostream class: This class is responsible for handling output stream. It provides number of function for handling chars, strings and objects such as write, put etc..

What is an Ostream?

ostream is a general purpose output stream. cout and cerr are both examples of ostreams. ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file. ofstream is an output file stream.


1 Answers

So far in my study of c++ I havent really come across ostream's and as such am not sure if its possible to explicitly create such a stream. I have tried using: std::ostream o;

You must have missed something, because ostreams are important. std::cout is a variable of type std::ostream by the way. Usage is more or less like this

#include <iostream> //defines "std::ostream", and creates "std::ofstream std::cout"
#include <fstream> //defines "std::ofstream" (a type of std::ostream)
std::ostream& doStuffWithStream(std::ostream &out) { //defines a function
    out << "apples!";
    return out;
}
int main() {
    std::cout << "starting!\n"; 
    doStuffWithStream(std::cout); //uses the function

    std::ofstream fileout("C:/myfile.txt"); //creates a "std::ofstream"
    doStuffWithStream(fileout); //uses the function

    return 0;
}
like image 114
Mooing Duck Avatar answered Oct 03 '22 23:10

Mooing Duck