Skip to content

Latest commit

 

History

History
102 lines (59 loc) · 4.64 KB

File metadata and controls

102 lines (59 loc) · 4.64 KB

 

 

 

 

 

 

operator>> (pronounced 'Stream in operator') is an operator for sending data from a stream to something. For doing the other way around, use operator<<.

 

 

 

 

 

 

Prefer overloading operator>> with a free function [1]. To be able to access the private member variables, make this function a friend.

 


#include <iostream>   struct MyClass {   MyClass(const int value) : mValue(value) {}   private:   int mValue;   friend std::istream& operator>>(std::istream& is, MyClass& myClass); };   std::istream& operator>>(std::istream& is, MyClass& myClass); {   is >> myClass.mValue;   return is; }   int main() {   MyClass myClass(13);   std::cin >> myClass; }

 

 

 

 

 

Another example

 

 


#include <cassert> #include <fstream> #include <iostream> #include <string> struct Person {   std::string m_name;   int m_birth_year; }; std::ostream& operator<<(std::ostream& os,const Person& p) {   os << p.m_name      << ' ' //Add either a space, tab or newline      << p.m_birth_year;   return os; } std::istream& operator>>(std::istream& is, Person& p) {   is     >> p.m_name     >> p.m_birth_year;   return is; } int main() {   //Create a Person and save it to file   {     Person p;     p.m_name = "Bilderbikkel";     p.m_birth_year = 1980;     std::ofstream f("tmp.txt");     f << p;   }   //Create a Person and save it to file   {     std::ifstream f("tmp.txt");     Person p;     f >> p;     assert(p.m_name == "Bilderbikkel");     assert(p.m_birth_year == 1980);   } }

 

 

 

 

 

 

  1. Herb Sutter. Exceptional C++. ISBN: 0-201-61562-2.