书上的这个C++程序为什么运行出问题?

[复制链接]
查看11 | 回复3 | 2011-4-16 11:56:16 | 显示全部楼层 |阅读模式
我在VC6.0下编写程序如下:
#include
using namespace std;
class complex
{
public:
complex(){real=0;imag=0;}
complex(double r,double i){real=r;imag=i;}
complex operator + (complex &c2);
friend ostream & operator <<(ostream &,complex &);
private:
double real;
double imag;
};
complex complex::operator +(complex &c2)
{return complex(real+c2.real,imag+c2.imag);}
ostream & operator <<(ostream &output,complex &c)
{
output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
return output;
}
int main()
{
complex c1(2,4),c2(6,10),c3;
c3=c1+c2;
cout<<c3;
return 0;
}
编译结果如下:
error C2248: 'real' : cannot access private member declared in class 'complex'
error C2248: 'imag' : cannot access private member declared in class 'complex'
error C2593: 'operator <<' is ambiguous
请教高手这是怎么回事。。 后来我把头文件变为 然后去掉using namespace std 却可以, 真奇怪

回复

使用道具 举报

千问 | 2011-4-16 11:56:16 | 显示全部楼层
这是VC里面名字空间处理的问题。你可以把这个<<函数定义在namespace std中:namespace std{/////////////////////////ostream & operator <<(ostream &output,complex &c){output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;return output;}}////////////////////////或者把friend的<<函数直接定义在类中:class complex{public: complex(){real=0;imag=0;} complex(doub
回复

使用道具 举报

千问 | 2011-4-16 11:56:16 | 显示全部楼层
换本书好了
回复

使用道具 举报

千问 | 2011-4-16 11:56:16 | 显示全部楼层
程序“?????
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行