重载输出操作符<<怎样定义为非成员函数?

anison 2008-06-15 08:55:37
如果定义为成员函数,不好用

#include <stdafx.h>
#include <iostream>
#include <string>

using namespace std;

class A{
public:
A(int i,const string &s):i(i),s(s){}
// 定义为成员函数时,this指针绑定到左操作数,所以用起来很不习惯哦
ostream& operator<<(ostream &os)
{
os<<i<<s;
return os;
}
private:
int i;
string s;
};

int main(int argc,char* argv[])
{
A a(88,"abc");
a<<cout; // 不习惯...
system("pause");
}



但是定义为非成员函数的话又不能直接访问A类里的private成员,如果定义GetValue之类的public函数也挺麻烦的
不知道怎么处理好
...全文
233 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
hjr08241 2009-10-14
  • 打赏
  • 举报
回复
class A{
friend ostream& operator < < (ostream &os, const A& a)
{
return os < < a.i < < a.s;
}
public:
A(int i,const string &s):i(i),s(s){}
// 定义为成员函数时,this指针绑定到左操作数,所以用起来很不习惯哦
ostream& operator < <(ostream &os)
{
os < <i < <s;
return os;
}
private:
int i;
string s;
};
当定义符合标准库iostream规范的输入或输出操作符的时候,必须使它成为非成员操作符。
我们不能将该操作符定义为类的成员,否则,左操作数将只能是该类类型的对象。
// if operator << is a member of Sales_item
Sales_item item;
item << cout;
这个用法与为其他类型定义的输出操作符的正常使用方式相反。如果想要支持正常的用法,则左操作数必须为ostream类型。如果该操作符是类的成员,则它必须是ostream类的成员,然而ostream类是标准库的组成部分,我们是不能为标准库的类增加成员的。
如果想要使用重载操作符为该类型提供IO操作,就必须将他们定义为非成员函数。IO操作符通常对非公用数据成员进行读写,因此,类通常将IO操作符设为友元。

anison 2008-06-15
  • 打赏
  • 举报
回复
哦....又忘了...
谢谢大家
mengde007 2008-06-15
  • 打赏
  • 举报
回复
建议将ostream类声明为友员
K行天下 2008-06-15
  • 打赏
  • 举报
回复

#include <iostream>
#include <string>

using namespace std;

class A{
public:
A(int i,const string &s):i(i),s(s){}
// 定义为成员函数时,this指针绑定到左操作数,所以用起来很不习惯哦
ostream& operator<<(ostream &os)
{
os<<i<<s;
return os;
}
friend ostream& operator << (ostream &os, const A& a)
{
return os << a.i << a.s;
}

private:
int i;
string s;
};

int main(int argc,char* argv[])
{
A a(88,"abc");
a<<cout; // 不习惯...
cout<<endl<<a<<endl; // 这样就习惯了吧
system("pause");
}



paidfighting 2008-06-15
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 tannoliu 的回复:]
声明为友元函数即可
[/Quote]
tannoliu 2008-06-15
  • 打赏
  • 举报
回复
声明为友元函数即可
wlmmlw 2008-06-15
  • 打赏
  • 举报
回复
class A{
friend ostream& operator << (ostream &os, const A& a)
{
return os << a.i << a.s;
}
public:
A(int i,const string &s):i(i),s(s){}
// 定义为成员函数时,this指针绑定到左操作数,所以用起来很不习惯哦
ostream& operator<<(ostream &os)
{
os<<i<<s;
return os;
}
private:
int i;
string s;
};

64,649

社区成员

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

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