【问题标题】:Class in C++ which implements streams实现流的 C++ 类
【发布时间】:2011-05-22 09:37:49
【问题描述】:

我想编写一个具有两个功能的类 Map:保存和加载。 我想使用流,所以我可以在我的程序中编写: ma​​p 会将地图加载到内存中,ma​​p >> "map name" 会保存我的地图。

不幸的是,在谷歌中我只能找到如何覆盖运算符'>>''

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

【问题讨论】:

    标签: c++ stream


    【解决方案1】:

    重载<<>> 运算符并将它们声明为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 &lt;&lt; "hello" &lt;&lt; "hi"; 可能意味着从 "hello" 和 "hi" 加载 obj?或按该顺序附加它们,这取决于您。另外obj &gt;&gt; "hello" &gt;&gt; "hi"; 可以表示将obj 保存在名为“hello”和“hi”的两个文件中

    【讨论】:

      【解决方案2】:

      这里是如何重载operator&lt;&lt;operator&gt;&gt; 的简单说明

      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

      【讨论】:

        猜你喜欢
        • 2012-01-05
        • 2011-02-28
        • 2016-04-08
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多