开发者

Class in C++ which implements streams

I want to write a class Map with two functions: save a开发者_运维知识库nd load. I'd like to use streams so I could write in my program: map << "map name" and it'd load a map to memory and map >> "map name" and it'd save my map.

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

Can You give me same hints how to do it ? Thanks for answer in advance.


overload the << and >> operators and declare them as friend to 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 in your purpose there interpretation of the returning of the object is upto you because obj << "hello" << "hi"; can mean load the obj from both "hello" and "hi" ? or append them in that order, it is upto you. Also obj >> "hello" >> "hi"; can mean save the obj in two files named "hello" and "hi"


Here is simple illustration 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-cases, it may not be desirable to two or more maps, into a single object. If that is so, then you can make the return type of the operator<< void.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜