I want to make a class of a student and take 3 inputs information and make an output of this file. How to this? This is my try:
#include
usi
C++ uses the stream paradigm to implement standard input/output.
Stream paradigm means that if you application wants to access/use a resource (A file, the console, etc) a stream acts as a mediator between your application and the resource:
ofstream +----+
+-------------------->|File|
| +----+
|
+------+------+
| Application |
+------+------+
|
| +-------+
+-------------------->|Console|
cout +-------+
It means every write/read operations you perform are really stream operations. The point of this is that stream operations are basically the same, independently of what type of resource (And what type of stream) are you using.
This allows us to implement a "generic" (Generic meaning valid for any type of stream/resource). How? Overloading C++ operators >> and <<.
For input operations (Input means receiving data from the stream and put it in our variable/object), we need to overload the >> operator as follows:
istream& operator>>(istream& is , MyClass& object)
{
is >> object.myClassAtributte; (1)
... //Same for every attribute of your class.
return is;
}
First, note that the input stream is passed by reference. By reference because streams are non-copyable (What exactly means to copy a stream? Copy the link between your app and the resource? That sounds ridiculous), and non-const beacuse you are going to modify the stream (You are going to write through it).
Finally, note that the function not returns void, returns a reference to the same stream that was passed to the function. That allows you to write concatenated-write/read sentences like cout << "Hello. " << "Im" << " Manu343726" << endl;
For output operations (Output means sending data to the stream), we need to overload the << operator, wich implementation is exactly the same:
ostream& operator<<(ostream& os , const MyClass& object)
{
os << object.myClassAtributte; (1)
... //Same for every attribute of your class.
return os;
}
Note that in this case, your object is passed const, beacuse we won't modify it (We will only read its attributes).
(1) Is preferable to implement this functions making them friend of your class, to allow us access to private/protected members.