C++:友元运算符重载函数

时间:2023-11-25 10:38:26

运算符重载函数:实现对象之间进行算数运算,(实际上是对象的属性之间做运算),包括+(加号)、-(减号)、*、/、=、++、--、-(负号)、+(正号)

运算符重载函数分为:普通友元运算符重载函数、成员友元运算符重载函数、成员运算符重载函数

运算符运算符重载函数按运算类型为:双目运算符重载函数,如加、减、乘、除、赋值;   单目运算符重载函数:自加、自减、取正负号

切记:成员运算符. 和->,sezeof等不能重载。运算符重载函数的参数至少有一个是类类型或引用类型,

下面为友元运算符重载函数举例:

 #include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r=0.0,double i=0.0);
void print();
//friend为友元函数的关键字,这两个符号运算符重载函数的参数类型至少有一个类类型或者类的引用
friend Complex operator+(Complex &a,Complex &b);
friend Complex operator-(Complex &a,Complex &b);
private:
double real;
double imag;
};
Complex::Complex(double r,double i) //在类外定义函数,需要用::作用域符号
{
real = r;
imag = i;
}
Complex operator+(Complex &a,Complex &b)
{
Complex temp; //创建一个临时对象
temp.real = a.real + b.real;
temp.imag = a.imag + b.imag;
return temp;
}
Complex operator-(Complex &a,Complex &b)
{
Complex temp; //创建一个临时对象
temp.real = a.real - b.real;
temp.imag = a.imag - b.imag;
return temp;
}
void Complex::print()
{
cout<<real;
if(imag>) cout<<"+";
if(imag!=) cout<<imag<<'i'<<endl;
}
int main(int agrs,const char *agrv[])
{
Complex A1(2.3,4.6),A2(3.6,2.8),A3,A4;
A3 = A1 + A2;//A3 = operator+(A1,A2); //对运算符重载函数的调用,前面的为隐式调用,后面的为显示调用
A4 = A1 - A2;//A4 = operator-(A1-A2);
A1.print();
A2.print();
A3.print();
A4.print(); return ;
}

运行结果:

2.3+.6i
3.6+.8i
5.9+.4i
-1.3+.8i
Program ended with exit code: