A class in C ++ that implements threads

I want to write a Map class with two functions: save and load. I would like to use streams to write in my program: map <"map name" , and it will load the map into memory and map → "map name" , and it will save my map.

Unfortunately, on google, I can only find how to override the operators → '' <<', but using cout or cin on the left side of the operator.

Can you give me the same hints how to do this? Thanks for the reply in advance.

+4
source share
2 answers

overload the << and >> operators and declare them as friend your class, and then use them. Here is a sample code.

 #include <iostream> #include <string> using namespace std; class Map { friend Map& operator << (Map &map, string str); friend Map& operator >> (Map &map, string str); }; Map& operator << (Map &map, string str) { //do work, save the map with name str cout << "Saving into \""<< str << "\"" << endl; return map; } Map& operator >> (Map &map, string str) { // do work, load the map named str into map cout << "Loading from \"" << str << "\"" << endl; return map; } int main (void) { Map map; string str; map << "name1"; map >> "name2"; } 

Note that for your purpose, the interpretation of the return of the object is up to you, because obj << "hello" << "hi"; can mean loading obj from "hello" and "hello"? or add them in this order, it is up to you. Also obj >> "hello" >> "hi"; may mean saving obj in two files named hello and hello

+3
source

Here is a simple illustration of how you can overload operator<< and operator>>

 class Map { Map & operator<< (std::string mapName) { //load the map from whatever location //if you want to load from some file, //then you have to use std::ifstream here to read the file! return *this; //this enables you to load map from //multiple mapNames in single line, if you so desire! } Map & operator >> (std::string mapName) { //save the map return *this; //this enables you to save map multiple //times in a single line! } }; //Usage Map m1; m1 << "map-name" ; //load the map m1 >> "saved-map-name" ; //save the map Map m2; m2 << "map1" << "map2"; //load both maps! m2 >> "save-map1" >> "save-map2"; //save to two different names! 

Depending on the use case, it may not be desirable to use two or more cards in the same facility. If so, then you can make the return type of the operator << void .

+2
source

All Articles