首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新手提问,有关问题挺多的

2013-03-01 
新手提问,问题挺多的本帖最后由 catonmoon 于 2013-02-23 12:17:14 编辑问题写在注释里了.#includeiostre

新手提问,问题挺多的
本帖最后由 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()才能让程序停下来,只用一个会直接关掉
}

[解决办法]
1,cc和&cc有什么区别,为什么cc.real可以访问而cc->real提示是不可访问?
答:cc,&cc区别在于,前面会调用复制构造函数,后面的不会,而且,前面的会产生副本,后面的不会
cc.real可以访问而cc->real,你可以去了解指针就知道区别了。
2,cin>>p;//为什么cin>>提示错误;
答:你传入的是p指针对象的地址,而非对象本身
3,为什么这里要两个getchar()才能让程序停下来,只用一个会直接关掉
答:可能是前面的getchar接受了输入流队列中的一个字符,而后面的时候等待输入下一个。
[解决办法]
1楼说的第一问有点问题,可能是看错了,你的第一个疑问是因为你的第一个>>重载是友元函数,而第二个不是友元函数当然没有权利去访问参数里的私有成员了

如果要用指针做参数你可以重新重载一下上面的函数,或者传入指针参数并取值
[解决办法]
你的类函数声明 friend部分为
friend CComplex operator * (CComplex cc1,CComplex cc2);    friend ostream &operator <<(ostream &output,CComplex &cc);    friend istream  &operator >>(istream &input,CComplex &cc);

再加一句
friend istream &operator >>(istream &i,CComplex *cc);
[解决办法]
你有没有发现你重载了4个operator,但是只有三个声明了friend,然后是没有问题的,有无想过原因。



[解决办法]
最后那个忘声明成友元函数了

热点排行