新手提问,问题挺多的
本帖最后由 catonmoon 于 2013-02-23 12:17:14 编辑 问题写在注释里了.
#include<iostream>
using namespace std;
class CComplex
{
public:
CComplex(double r=0.0,double i=0.0)
{
real=r;
image=i;
}
~CComplex(){}
friend CComplex operator * (CComplex cc1,CComplex cc2);
friend ostream &operator <<(ostream &output,CComplex &cc);
friend istream &operator >>(istream &input,CComplex &cc);
private:
double real;
double image;
};
CComplex operator * (CComplex cc1,CComplex cc2)
{
CComplex temp;
temp.real =cc1.real+cc2.real;
temp.image=cc1.image+cc2.image;
return(temp);
}
ostream &operator << (ostream &output,CComplex &cc)
{
if(cc.real!=0)
{
output<<cc.real;
if(cc.image==0)
return output;
else
if(cc.image>0)
{
output<<'+'<<cc.image<<'i'<<endl;
return output;
}
else
{
output<<cc.image<<'i'<<endl;
return output;
}
}
else
{
if(cc.image==0)
{
output<<0<<endl;
return output;
}
else
{
output<<cc.image<<'i'<<endl;
return output;
}
}
}
istream &operator >>(istream &i,CComplex &cc)
{
i>>cc.real>>cc.image;
return i;
}
/*
*cc和&cc有什么区别,为什么cc.real可以访问而cc->real提示是不可访问??
istream &operator >>(istream &i,CComplex *cc)
{
i>>cc->real>>cc->image;
return i;
}
*/
void main()
{
CComplex c1,c2(5.9,9.7);
cout<<c2;
cout<<"please enter..."<<endl;
cin>>c1;
cout<<c1;
/*
CComplex * p=new CComplex(9,9);
cin>>p;//为什么cin>>提示错误;
cout<<p;//而cout<<没有问题;
*/
getchar();
getchar();//为什么这里要两个getchar()才能让程序停下来,只用一个会直接关掉
}
friend CComplex operator * (CComplex cc1,CComplex cc2); friend ostream &operator <<(ostream &output,CComplex &cc); friend istream &operator >>(istream &input,CComplex &cc);
[解决办法]
最后那个忘声明成友元函数了