以下程序使用友元函数重载<<、>>,使之能适用于复数类:
#include<iostream.h>
class Complex
{
double Real, Image;
public:
Complex(double r=0, double i=0)
{
Real=r; Image=i;
}
friend istream& operator>>(istream &, Complex &);
friend ostream& operator<<(ostream &, Complex &);
};
istream& operator>>(istream &in, Complex &c)
{
in>>c.Real>>c.Image;
return in;
}
ostream& operator<<(ostream &out, Complex &c)
{
out<<c.Real;
if(c.Image>0) out<<'+'<<c.Image<<'i';
else if(c.Image<0) out<<c.Image<<'i';
out<<endl;
return out;
}
void main( )
{
Complex c1(1, 2), c2;
cout<<c1;
cout<<"Please input c1 & c2:\n";
cin>>c1>>c2;
cout<<c1<<c2;
}
此程序可以正确运行,但是一旦将#include<iostream.h>改成
#include<iostream>
using namespace std;
编译就无法通过了,提示说重载运算符的函数不能访问Complex的私有成员,请问这是什么道理?这两种用法到底有何区别?这个程序怎样能改成使用第二种写法的正确程序呢?
明月笑刀无情
湖上湖
qq_花开花谢_0