友元成员函数的问题
#include<iostream.h>
class complex
{
private:
double real;
double imag;
public:
complex(double r=0,double i=0);
void print()
friend complex operator +(complex a,complex b);
};
complex::complex(double r,double i)
{
real=r;
imag=i;
}
complex operator +(complex a,complex b)
{
complex temp;
temp.real=a.real+b.real;
temp.imag=a.imag+b.imag;
return temp;
}
void complex::print()
{
cout<<real;
if(imag>0)
cout<<"+";
if(imag!=0)
cout<<imag<<"i"<<endl;
}
main()
{
complex x1(3,5),x2(5,9),x3;
x3=x1+x2;
x3.print();
return 0;
}
此程序在类内的void print()加个";",便可以运行。
但print()后没有";",程序便有八个错误。
“ cpp(20) : error C2248: 'real' : cannot access private member declared in class 'complex' ”
怎么分析这个错误?
print()函数应该和下面的friend operator+(complex a,complex b)函数没有联系
即使少了个“;”,也只是语法错误。这是怎么回事?