C++中实现流的类

4
我想写一个名为Map的类,其中包含两个函数:save和load。我希望使用流来实现,在我的程序中可以这样写:map << "地图名称" 将一张地图加载到内存中,map >> "地图名称" 则会保存我的地图。
不幸的是,在Google上我只能找到如何重载运算符'>>'和'<<',但是在运算符的左边使用cout或cin。
您能给我一些提示吗?感谢您提前的答复。
2个回答

3

重载 <<>> 运算符并将它们声明为你的类的 friend,然后使用它们。这里是一个样例代码。

#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";
}

请注意,在您的目的中,对象返回的解释取决于您,因为obj << "hello" << "hi";可以意味着从“hello”和“hi”同时加载obj,还是按照顺序附加它们,这由您决定。此外,obj >> "hello" >> "hi";可以意味着将obj保存在名为“hello”和“hi”的两个文件中。

2

这里是一个简单的示例,展示了如何重载operator<<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!

根据使用情况,将两个或多个地图合并为单个对象可能是不可取的。如果是这样,您可以将operator<<的返回类型设置为void


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接