#include <iostream> using namespace std; class myComplex { private: double real, imag; public: myComplex(); myComplex(double r,double x); friend myComplex addCom(myComplex c1, myComplex c2); //两个参数对象c1 与 c2相加 friend void outCom(myComplex c); }; myComplex::myComplex() { real = 0; imag = 0; } myComplex::myComplex(double r, double i) { real = r; imag = i; } myComplex addCom(myComplex c1, myComplex c2) { return myComplex(c1.real + c2.real, c1.imag + c2.imag); } void outCom(myComplex c) { cout << "(" << c.real << "," << c.imag << ")"; } int main() { myComplex c1(1, 2), c2(3, 4), res; res = addCom(c1, c2);//调用友元函数不通过类对象 outCom(c1); cout << "+"; outCom(c2); cout << "="; outCom(res); cout << endl; return 0; }
运行结果:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。