首页 > 学院 > 开发设计 > 正文

友元函数与运算符重载的结合

2019-11-08 01:17:02
字体:
来源:转载
供稿:网友

写在前面

之前的文章阐述了友元函数和友元类和运算符重载,当运算符重载需要调用原类的私有成员或保护成员时,需要将运算符函数声明为友元函数。

例子

#include<iostream>using namespace std;class Complex{// 复数类 double real, imag;// 实部和虚部public: Complex(){ real = imag = 0; }; Complex(double r, double i){ real = r; imag = i; } friend Complex Operator + (Complex, Complex);// 友元+运算符重载:两复数相加 friend Complex operator - (Complex, Complex);// 友元+运算符重载:两复数相减 friend void PRintComplex(Complex c);// 输出复数};Complex operator + (Complex c1, Complex c2){ Complex c; c.real = c1.real + c2.real; c.imag = c1.imag + c2.imag; return c;}Complex operator - (Complex c1, Complex c2){ Complex c; c.real = c1.real - c2.real; c.imag = c1.imag - c2.imag; return c;}void printComplex(Complex c){ cout << c.real << "+" << c.imag << "i";}int main(){ Complex c1(1, 2), c2(3, 4); cout << "c1: "; printComplex(c1); cout << endl; cout << "c2: "; printComplex(c2); cout << endl; cout << "c1+c2: "; printComplex(c1 + c2); cout << endl; cout << "c1-c2: "; printComplex(c1 - c2); cout << endl;}

运行结果

c1: 1+2ic2: 3+4ic1+c2: 4+6ic1-c2: -2+-2i
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表