寫在前面
之前的文章闡述了友元函數和友元類和運算符重載,當運算符重載需要調用原類的私有成員或保護成員時,需要將運算符函數聲明爲友元函數。
例子
#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+2i
c2: 3+4i
c1+c2: 4+6i
c1-c2: -2+-2i