重载运算符问题?

lxjjoinly 2007-12-11 11:54:35
#include <iostream>
#include <cstring>
using namespace std;

class A{
char name[32];
int areacode;
int prefix;
int num;
public:
A(char *s,int i,int j,int k)
{
strcpy(name,s);
areacode = i;
prefix = j;
num = k;
}
friend ostream &operator<<(ostream &stream,A o);
};
ostream &operator<<(ostream &stream,A o)
{
stream<<o.name<<" ";
stream.fill('0');
stream.width(3);
stream<<"("<<o.areacode<<") ";
stream.width(8);
stream<<o.prefix<<"-";
stream.width(4);
stream<<o.num<<endl;
return stream;
}
int main()
{
A ob1("AAA",111,22222,333);
A ob2("BBB",444,55555,666);
A ob3("CCC",777,88888,999);
cout<<ob1<<ob2<<ob3;
return 0;
}

刚想学C++,书上抄了个例程,就编译不了........打击我的信心啊 -_-!!!!!!!!
1.说是不能访问私有变量.......晕,我用的是友元啊
2.说'operator >>'不明确?该怎么改啊,让它能够明确点!!!!哈哈
...全文
82 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
WeinJones 2007-12-11
  • 打赏
  • 举报
回复
晕,哪本书上写这样滴例子啊?
yydrewdrew 2007-12-11
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstring>
using namespace std;
class A;
ostream &operator<<(ostream &stream,A o);
class A
{
char name[32];
int areacode;
int prefix;
int num;
public:
A(char *s,int i,int j,int k)
{
strcpy(name,s);
areacode = i;
prefix = j;
num = k;
}
friend ostream &operator<<(ostream &stream,A o);
};

ostream &operator<<(ostream &stream,A o)
{
stream<<o.name<<" ";
stream.fill('0');
stream.width(3);
stream<<"("<<o.areacode<<") ";
stream.width(8);
stream<<o.prefix<<"-";
stream.width(4);
stream<<o.num<<endl;
return stream;
}
int main()
{
A ob1("AAA",111,22222,333);
A ob2("BBB",444,55555,666);
A ob3("CCC",777,88888,999);
cout<<ob1<<ob2<<ob3;
return 0;
}
SimonFu 2007-12-11
  • 打赏
  • 举报
回复
没问题啊,2003

>>不明确,程序中我咋找不到定位呢
effective_person 2007-12-11
  • 打赏
  • 举报
回复

#include <iostream>
#include <cstring>
using namespace std;
class A{
char name[32];
int areacode;
int prefix;
int num;
public:
A(char *s,int i,int j,int k)
{
strcpy(name,s);
areacode = i;
prefix = j;
num = k;
}
friend ostream &operator<<(ostream &stream,A o)
{
stream<<o.name<<" ";
stream.fill('0');
stream.width(3);
stream<<"("<<o.areacode<<") ";
stream.width(8);
stream<<o.prefix<<"-";
stream.width(4);
stream<<o.num<<endl;
return stream;
}
};
int main()
{
A ob1("AAA",111,22222,333);
A ob2("BBB",444,55555,666);
A ob3("CCC",777,88888,999);
cout<<ob1<<ob2<<ob3;
return 0;
}

楼主应该用的vc6.0
vc6.0 不支持friend 函数再类外定义 最好把函数设为内置函数
ar_2002 2007-12-11
  • 打赏
  • 举报
回复
环境BCB6 没有问题 楼主换个编译器看看
arfi 2007-12-11
  • 打赏
  • 举报
回复
可能是编译器的BUG

将包含的头文件替换为
#include <iostream.h>
#include <string.h>

或者将定义写在类里面,就可以编译通过
freshairfly 2007-12-11
  • 打赏
  • 举报
回复
我编译没问题啊,我的是VC2003
jameshooo 2007-12-11
  • 打赏
  • 举报
回复
把函数原型改写成 ostream &operator<<(ostream &stream,A& o) 试试
lxjjoinly 2007-12-11
  • 打赏
  • 举报
回复
哦,谢谢啊,我用的就是VC6.0啊
书名《C++参考大全第四版》

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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