【发布时间】:2011-05-22 09:37:49
【问题描述】:
我想编写一个具有两个功能的类 Map:保存和加载。 我想使用流,所以我可以在我的程序中编写: map 会将地图加载到内存中,map >> "map name" 会保存我的地图。
不幸的是,在谷歌中我只能找到如何覆盖运算符'>>''
你能给我同样的提示吗? 感谢您提前回答。
【问题讨论】:
我想编写一个具有两个功能的类 Map:保存和加载。 我想使用流,所以我可以在我的程序中编写: map 会将地图加载到内存中,map >> "map name" 会保存我的地图。
不幸的是,在谷歌中我只能找到如何覆盖运算符'>>''
你能给我同样的提示吗? 感谢您提前回答。
【问题讨论】:
重载<< 和>> 运算符并将它们声明为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。
【讨论】: