Input and output operators (>>
and <<
) can be predefined too.
Those operators can only be predefined outside the class.
Syntax:
Notice that the class object is passed by reference (using &
).
This way the class object can be modified inside the function.
Example:
User's input:
Output:
>>
operator is called at line 47
and
predefined at lines 30 - 42
.
Syntax:
Example:
Output:
<<
operator is called at line 41
and predefined at lines 30 - 36
.
So far the only stream that was used is the console - through cin
and cout
.
Except the console we can also use other streams (like the file stream) for the predefined input and output operators.
Let's use the file stream.
So if we have input-file.txt
with content:
And the following cpp code:
Then the console result would be:
Also a file named output-file.txt
will be created with content:
Explanation:
lines 66
input-file.txt
file is opened.line 67
the file content is red and member's values are set
for the personFromInputFile
object.
operator>>
function (lines 46 - 58
).
line 70
personFromInputFile
object is
printed. It's name
and age are the same as those specified
in the input-file.txt
file.line 80
the name and age are written in the
"output-file.txt
. The way the are written
is specified in the operator<<
function
(lines 37 - 43
).