关于“重载运算符和友元函数参数关系”的问题
程序代码:
//重载运算符和友元函数 #include<iostream> using namespace std; class Complex { public: Complex( ){ real=0;imag=0;} Complex( double r,double i):real(r),imag(i){ } friend Complex operator + (Complex &c1,Complex &c2); //重载函数作为友元函数 void display( ); private: double real; double imag; }; Complex operator + (Complex &c1,Complex &c2) //定义作为友元函数的重载函数 { return Complex(c1.real + c2.real,c1.imag + c2.imag);} void Complex::display( ) { cout << "(" << real << "," << imag <<"i)" << endl;} int main( ) { Complex c1(3,4),c2(5,-10),c3; c3 = c1 + c2; cout << "c1 = ";c1.display( ); cout << "c2 = ";c2.display( ); cout << "c1 + c2 = ";c3.display( ); system("pause"); return 0; } /* 请问:如果想把类中申明友元函数的 friend 去掉,就是说,把 Complex operator+ ( Complex &c1,Complex &c2) 作 为 Complex 类的成员函数,行不行呢?为什么?你能保证在有两个参数的前提下,不用友元关系,使程序正常运行吗? */