如何用成员函数的方式重载输出操作符<<

如何用成员函数的方式重载输出操作符<<和输入操作业符>>最好可给出一个示例代码,谢谢!... 如何用成员函数的方式重载输出操作符<< 和输入操作业符>>

最好可给出一个示例代码,谢谢!
展开
 我来答
qizhi0119
2007-12-12 · TA获得超过357个赞
知道小有建树答主
回答量:510
采纳率:0%
帮助的人:272万
展开全部
我也才学了不久,但是,我记得我看的书上(谭浩强,C++面向对象)说的是提取,和插入运算符只能做为友元函数来重载。
因为正常的重载(成员函数时),比如,
类型名 operator 运算符(参数类型 参数名);
他是将本类的对象,默认成第一个参数了,
调用时,就相当于(比如对象是c1,运算符为'+',后面的参数为c2)c1.operator+(c2);这样,也就可以相当于调用的是c1的成员函数,所以,c1必须是此类的对象。这种可以简写成c1+c2;
而<<和>>都会写成cout<<,cin>>这种形式,
其实,相当于operator <<(cout,对象2),然后把cout提前了,
cout是ostream类的一个对象,和上面类似,也就是,这两个运算符的重载第一个参数,是ostream的对象,或是istream的对象,而第二个参数才是你定义的类的对象。因此,不能用成员函数做重载,只能用做友元,不过vc++6.0中,不加.h的头文件是不支持这种友元重载的,
所以,如果用的是vc++6.0编译的话,可以将#include <iostream>
这种,文件包含改为#include <iostream.h>所有的包含都用带.h的。
然后去掉using namespace std;
絕望de生魚片
2007-12-12 · TA获得超过121个赞
知道答主
回答量:71
采纳率:0%
帮助的人:0
展开全部
你要想把 操作符"<<" ">>"重载为 成员函数 ,就要修改 头文件·· 你为了实现自己的一个功能而去修改头文件,显然不可取··
建议你将 操作符"<<" ">>"重载为 你要操作类非成员函数(友元函数或普通函数)~~
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
isjk
2007-12-12 · TA获得超过793个赞
知道答主
回答量:195
采纳率:0%
帮助的人:49万
展开全部
类里面声明用
class obj
{
public:
int x,y;
friend ostream& operator<<(ostream& os,obj& rhs);
}
实现的时候用:
ostream& operater<<(ostream& os,obj& rhs)
{
os<<rhs.x<<rhs.y;
return os;
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
flying_search
2007-12-12 · TA获得超过131个赞
知道答主
回答量:207
采纳率:0%
帮助的人:0
展开全部
#include <iostream>
using namespace std;
class Point
{
int x;
int y;
public:
Point():x(1),y(1){}//构造函数
Point& operator++();//前++
Point operator++(int);//后++
friend Point& operator--(Point& a);//前--
friend Point operator--(Point& a, int);//后--
friend ostream& operator<<(ostream& output, Point& p);//重载输出
friend Point operator+(Point& a,Point& b);//重载+
friend Point operator-(Point& a,Point& b);//重载-

};
Point& Point::operator ++()//前++
{
++x;
++y;
return *this;
}
Point Point::operator ++(int)//后++
{
Point temp=*this;
++x;
++y;
return temp;
}
Point& operator--(Point& a)//前--
{
--(a.x);
--(a.y);
return a;
}
Point operator--(Point& a,int)//后--
{
Point temp=a;
--(a.x);
--(a.y);
return temp;
}
Point operator+(Point& a,Point& b)//+
{
Point temp;
temp.x=b.x+a.x;
temp.y=b.y+a.y;
return temp;
}
Point operator-(Point& a,Point& b)//重载-
{
Point temp;
temp.x=a.x-b.x;
temp.y=a.y-b.y;
return temp;
}
ostream& operator<<(ostream& output, Point& p)
{
output << p.x <<endl;
output << p.y <<endl;
return output;
}
int main()
{
Point p;
Point p2;
/*cout << p;
++p;
cout << p;
p++;
cout << p;
--p;
cout << p;
p--;
cout << p; */
Point temp=++p+p2++;
cout << temp;
cout << p;
cout << p2;
temp=++p-p2--;
cout << temp;
cout << p;
cout << p2;
return 0;
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式