实现流的类C++
Class in C++ which implements streams
我想写一个具有两个函数的类 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
。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的