这重载操作符哪里错了?。。帮我看看谢谢~~~

touchwhat 2009-03-25 05:06:04
#include <iostream>
using namespace std;
class testclass{
public:
int a, b;
testclass(int a1, int b1){
a = a1, b = b1;
}

friend ostream & operator <<(ostream & os, testclass a1){
cout << "a = " << a1.a << ", b = " << a1.b << endl;
return os;
}

friend ostream & operator <<(ostream & os, testclass *a1){
cout << "a = " << a1->a << ", b = " << a1->b << endl;
return os;
}

friend istream& operator >>(istream &in,const testclass &b1)
{
in>>b1.a;
return in;
}
friend ostream & operator <<(ostream & os, testclass *b1){
cout << "b1="<<b1.a<<endl;
return os;
}
};//end of testclass

int main(){
testclass *a1 = new testclass(1, 2);
cout << a1;
cout << *a1;
testclass b3(4,5);
cin>>b3;
cout<<b3;

return 0;
}
...全文
94 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
leewon1988 2009-03-25
  • 打赏
  • 举报
回复
正解
[Quote=引用 5 楼 douyangyang 的回复:]
有两个问题:

1.你定义的第二个运算符和你的第四个运算符重复了
friend ostream & operator < <(ostream & os, testclass *a1) {...}

friend ostream & operator < <(ostream & os, testclass *b1) {...}

这两个只有参数的名字不一样,这是重复定义

2.第三个运算符
friend istream& operator >>(istream &in,const testclass &b1) {...}
应该把第二个参数的const去掉,因为你会在其中修改b1的值。
[/Quote]
liusichen_0 2009-03-25
  • 打赏
  • 举报
回复

liusichen_0 2009-03-25
  • 打赏
  • 举报
回复
这里还有一点问题
[code=c/c++]
friend ostream & operator <<(ostream & os, testclass *b1){
cout << "b1="<<b1.a<<endl; // 怎么不是b1->a呢
[/code]
  • 打赏
  • 举报
回复
friend istream& operator >>(istream &in,const testclass &b1)
{
in>>b1.a;
return in;
}
应该是这里了,const对象接收流
douyangyang 2009-03-25
  • 打赏
  • 举报
回复
有两个问题:

1.你定义的第二个运算符和你的第四个运算符重复了
friend ostream & operator <<(ostream & os, testclass *a1) {...}

friend ostream & operator <<(ostream & os, testclass *b1) {...}

这两个只有参数的名字不一样,这是重复定义

2.第三个运算符
friend istream& operator >>(istream &in,const testclass &b1) {...}
应该把第二个参数的const去掉,因为你会在其中修改b1的值。
mengde007 2009-03-25
  • 打赏
  • 举报
回复
friend istream& operator >>(istream &in,const testclass &b1)
{
in>>b1.a;//b1都为const 了,那还能操作啊!把const去掉
return in;
}
testclass *a1 = new testclass(1, 2);
//似乎没有delete;
downmooner 2009-03-25
  • 打赏
  • 举报
回复
函数里的.
downmooner 2009-03-25
  • 打赏
  • 举报
回复
cout cin 换成你的形参
lgccaa 2009-03-25
  • 打赏
  • 举报
回复
报什么错?把错误信息贴出来

65,211

社区成员

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

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