输出流和输入流的重载问题

cutrain2009 2009-08-30 03:50:44
一般情况下输入流和输出流是定义为该类的友元函数

我尝试在类内重载
virtual ostream& operator<<(ostream& out)
{
out<<m_nID<<" "<<m_strName.GetBuffer(MAX_PATH);
m_strName.ReleaseBuffer();
return out;
}

virtual istream& operator>>(istream& in)
{
UINT m_nTemp;
char strTemp[1024];
in>>m_nTemp>>strTemp;
m_nID=m_nTemp;
m_strName=strTemp;
return in;
}

这是一个CEntity的类内

CPlayer 从CEntity中派生

virtual ostream& operator<<(ostream& out)
{
out<<m_nID<<" "<<m_strName.GetBuffer(MAX_PATH);
m_strName.ReleaseBuffer();
return out;
}

virtual istream& operator>>(istream& in)
{
UINT m_nTemp;
char strTemp[1024];
in>>m_nTemp>>strTemp;
m_nID=m_nTemp;
m_strName=strTemp;
return in;
}

我这使用了虚函数,

要不就会发现在对CPlayer进行输入输出流时会只调用CEntity的重载函数;

编译时出错
ompiling...
Game.cpp
E:\mud\3\Game.cpp(48) : error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'class CPlayer' (or there is no acceptable conversion)
E:\mud\3\Game.cpp(84) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class CPlayer' (or there is no acceptable conversion)


ifile>>m_Player;

其中ifile是一个输入文件

我这样的处理方式只是尝试的这样处理,因为我很想把所有的运输封装在类内,请大家提提已经
类内这样定义重载的是输入流和输出流的运算啊
...全文
191 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
cutrain2009 2009-08-31
  • 打赏
  • 举报
回复
我只是一个新手,
想尝试下,
至于工作吗???
我还在读本科,还有几年
taodm 2009-08-31
  • 打赏
  • 举报
回复
真的写出这样代码的人,离被开掉的日子也不会远了。
pengzhixi 2009-08-31
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wisaa 的回复:]
引用 1 楼 pengzhixi 的回复:
operator>>请用友元来重载。别作为成员函数。
不是一样吗
[/Quote]

请去看看操作符重载
cutrain2009 2009-08-31
  • 打赏
  • 举报
回复
呵呵,
说实话,我蛮喜欢这样处理的

obj < <cout
wisaa 2009-08-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 pengzhixi 的回复:]
operator>>请用友元来重载。别作为成员函数。
[/Quote]不是一样吗
mstlq 2009-08-30
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 cutrain2009 的回复:]
为什么要这样处理,
不能封装在类内吗
[/Quote]

如果楼主喜欢obj <<cout这样的写法的话,放类里面未尝不可,不过一般人都不习惯,看着眼晕……
jinwei1984 2009-08-30
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 cutrain2009 的回复:]
为什么要这样处理,
不能封装在类内吗
[/Quote]

这样就不符合输入输出时的习惯
第一个参数必须为类的对象,否则使用的时候必须像下面这样
obj<<cout
而不是cout<<obj
cutrain2009 2009-08-30
  • 打赏
  • 举报
回复
为什么要这样处理,
不能封装在类内吗
pengzhixi 2009-08-30
  • 打赏
  • 举报
回复
operator>>请用友元来重载。别作为成员函数。

64,639

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧