sy4_多态的应用_2.2_运算符重载为友元函数
(2)设计程序实现复数的加法和乘法运算,要求使用两种方法实现:第二种方法:将加法运算符和乘法运算符重载为友元函数, 使之能够实现复数的加法和乘法运算。
实现思路:
运算符重载为类的友元函数的一般格式为:
friend 函数类型 operator 运算符名称(形参列表)
{
对运算符的重载处理
}
当运算符重载为类的友元函数时,由于没有隐含的this指针,因此操作数的个数没有变化,所有的操作数都必须通过函数的形参进行传递,函数的参数与操作数自左至右一一对应。
调用友元函数运算符的格式如下:
operator 运算符 (参数1,参数2)
它等价于
<参数1> 运算符 <参数2>
例如:
operator+(a,b)等价于a+b
一般情况下,单目运算符最好重载为类的成员函数,双目运算符则最好重载为类的友元函数。
friend Complex operator+(const Complex &c1, const Complex &c2);
friend Complex operator*(const Complex &c1, const Complex &c2);
友元函数
Complex operator+(const Complex& c1, const Complex& c2)
{
Complex x;
x.real = c1.real + c2.real;
x.imag = c1.imag + c2.imag;
return x;
}
Complex operator*(const Complex& c1, const Complex& c2)
{
Complex y;
y.real = c1.real * c2.real - c1.imag * c2.imag;
y.imag = c1.real * c2.imag + c1.imag * c2.real;
return y;
}
整段代码:
#include <iostream>
#include "math.h";
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex();
Complex(double r, double i);
void display();
friend Complex operator+(const Complex &c1, const Complex &c2);
friend Complex operator*(const Complex &c1, const Complex &c2);
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
void Complex::display()
{
if (imag != 0)//虚数a±bi
{
if (real != 0)//虚数a±bi
{
if (imag > 0)//虚数a+bi
{
cout << "虚数=" << real << "+" << imag << "i" << endl;
}
else//虚数a-bi
{
cout << "虚数=" << real << imag << "i" << endl;
}
}
else//纯虚数bi
{
cout << "纯虚数=" << imag << "i" << endl;
}
}
else//实数a
{
cout << "实数=" << real << endl;
}
}
Complex operator+(const Complex& c1, const Complex& c2)
{
Complex x;
x.real = c1.real + c2.real;
x.imag = c1.imag + c2.imag;
return x;
}
Complex operator*(const Complex& c1, const Complex& c2)
{
Complex y;
y.real = c1.real * c2.real - c1.imag * c2.imag;
y.imag = c1.real * c2.imag + c1.imag * c2.real;
return y;
}
int main()
{
Complex c1(5, 0), c2(0, 5), c3(5, 4), c4(3, -2);
Complex S, P;
cout << "c1为";
c1.display();
cout << "c2为";
c2.display();
cout << "c3为";
c3.display();
cout << "c4为";
c4.display();
cout << "c3+c4为";
S = operator+(c3,c4); //S = c3 + c4;
S.display();
cout << "c3*c4为";
P = operator*(c3,c4); //P = c3 + c4;
P.display();
return 0;
}