注册 登录
编程论坛 C++教室

友元重载输入输出

usebird 发布于 2007-07-27 19:05, 1634 次点击

情况是这样的,我编了一个复数类,然后用友元重载输入输出,可是我对输入输出流类不是很清楚。于是写了函数声明后发现函数体无从下手,就请教一下,输入输出流类究竟有哪些成员和成员函数这两个函数究竟结构如何,如何实现功能。
friend istream &operator>>(istream &is,CComplex &com);
friend ostream &operator<<(ostream &os,CComplex &com);
CComplex是我定义的复数类。

13 回复
#2
野比2007-07-27 19:20

定义左右操作数(你的没错)... 然后在里面比如这样

cout<<com.real<<"+"<<com.img<<"i";

就实现了...
然后用的时候
CComplex x;
x.real=3;
x.img=4;
cout<<"x="<<x;

最后输出:

x=3+4i

#3
usebird2007-07-27 20:13
斑竹,这是输出呀,输入怎么办呢?
#4
usebird2007-07-27 20:39
ostream ostream::operator<<(ostream &os,CComplex &com)这是我定义的实现部分函数头

error C2511: '<<' : overloaded member function 'class ostream (class ostream &,class CComplex &)' not found in 'ostream'
这是错误
怎么回事,应该没错呀
#5
aipb20072007-07-27 22:07
friend istream &operator>>(istream &is,CComplex &com);

friend ostream &operator<<(ostream &os,const CComplex &com);//也可以对常量操作


函数原形就是这样,你上面的错了,ostream ostream::operator<<( 这个确实匪夷所思。
#6
usebird2007-07-28 10:02

继续请教
输出解决了,输入怎么办?
给个建议
输入形式是a+bi和a+b*i

#7
aipb20072007-07-28 10:26
friend istream &operator>>(istream &is,CComplex &com){
char c;
is >> com.r >> c >> com.i >> c;
}

[此贴子已经被作者于2007-7-28 11:06:10编辑过]

#8
usebird2007-07-28 10:32
thank you
和我的差不多
不过斑竹忘了return is;了
#9
aipb20072007-07-28 10:36
呵呵~
#10
usebird2007-07-28 10:43

斑竹,还有个问题
因为输入格式有两种(a+bi和a+b*i)
我的程序段是这样的
istream &operator>>(istream &is,CComplex &com)
{
char c1,c2,c3=0;
do{
is>>com.Real>>c1>>com.Image>>c2>>c3;
}while(c1!='+'||c2!='i');
return is;
}
可是,只能有一种输入格式
请斑竹帮忙改一下

#11
aipb20072007-07-28 10:51
friend istream &operator>>(istream &is,CComplex &com){
char c;
is >> com.r >> c >> com.i >> c;
if (c == '*')
is >> c;
return is;
}

[此贴子已经被作者于2007-7-28 11:05:41编辑过]

#12
usebird2007-07-28 10:59
斑竹 5个错误

error C2018: unknown character '0xa3'
E:\c++\1.cpp(56) : error C2018: unknown character '0xbb'
E:\c++\1.cpp(57) : error C2146: syntax error : missing ';' before identifier 'is'
E:\c++\1.cpp(57) : error C2039: 'r' : is not a member of 'CComplex'
E:\c++\1.cpp(8) : see declaration of 'CComplex'
E:\c++\1.cpp(57) : error C2039: 'i' : is not a member of 'CComplex'
E:\c++\1.cpp(8) : see declaration of 'CComplex'
Error executing cl.exe.
#13
usebird2007-07-28 11:02
斑竹我错了,
你的一个中文分号没看到
#14
野比2007-07-28 18:36

输入和输出是一样的

1