实现流的类C++

Class in C++ which implements streams

本文关键字:C++ 实现      更新时间:2023-10-16

我想写一个具有两个函数的类 Map:save 和 load。我想使用流,这样我就可以在我的程序中编写: 地图<<"地图名称",它会将地图加载到内存中,并>>"地图名称"映射,然后保存我的地图。

不幸的是,在谷歌中,我只能找到如何覆盖运算符">>"<<",但在运算符的左侧使用 cout 或 cin。

你能给我同样的提示怎么做吗?感谢您提前回答。

重载<<>>运算符,并将它们声明为类的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"的两个文件中

这是一个简单的插图,说明如何重载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!

根据用例的不同,可能不希望将两个或多个映射放入单个对象中。如果是这样,则可以将运算符的返回类型设为<<void