C++ 类它实现了流
我想编写一个具有两个功能的类 Map:保存和加载。 我想使用流,这样我就可以在我的程序中编写: 地图<< “地图名称”,它会将地图加载到内存中,并地图>> “地图名称”,它会保存我的地图。
不幸的是,在谷歌中我只能找到如何覆盖运算符“>>” '<<',但在运算符左侧使用 cout 或 cin。
你能给我同样的提示吗? 感谢您提前答复。
I want to write a class Map with two functions: save and load.
I'd like to use streams so I could write in my program:
map << "map name" and it'd load a map to memory and map >> "map name" and it'd save my map.
Unfortunately in google I can only find how to override the operators '>>' '<<',but using cout or cin at the left side of the operator.
Can You give me same hints how to do it ?
Thanks for answer in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重载
<<
和>>
运算符并将它们声明为类的friend
,然后使用它们。这是示例代码。请注意,根据您的目的,对对象返回的解释取决于您,因为
obj << “你好”<< "hi";
可以意味着从 "hello" 和 "hi" 加载obj
吗?或按该顺序附加它们,这取决于您。还有obj >>> “你好”>> "hi";
可以表示将obj
保存在名为“hello”和“hi”的两个文件中overload the
<<
and>>
operators and declare them asfriend
to your class, and then use them. Here is a sample code.Note that in your purpose there interpretation of the returning of the object is upto you because
obj << "hello" << "hi";
can mean load theobj
from both "hello" and "hi" ? or append them in that order, it is upto you. Alsoobj >> "hello" >> "hi";
can mean save theobj
in two files named "hello" and "hi"以下是如何重载
operator<<
和operator>>
的简单说明,具体取决于用例,可能不需要将两个或多个映射放入单个对象。如果是这样,那么您可以将运算符<<的返回类型设置为
void
。Here is simple illustration how you can overload
operator<<
andoperator>>
Depending on the use-cases, it may not be desirable to two or more maps, into a single object. If that is so, then you can make the return type of the operator<<
void
.