C++重载操作符的优先级

时间:2023-01-16 08:56:50


重载操作符不能改变操作符的优先级和语法特性。例如上一节复数类中的加法操作符重载函数,重载后加法的优先级仍然保持不变,重载后仍然为二元操作符。

 &#160继续沿用上一节例 1 中的 complex 复数类,我们定义了该类的四个对象,然后进行四则运算,c4=c1+c2c3;语句等同于c4=c1+(c2c3);,虽然在复数类中重载了加减乘数四个操作符,但是并不会改变它们为二元操作符的特性,同时也不会改变它们的优先级,因此对于重载后的加法操作符而言,其优先级是低于乘法操作符的。

#include <iostream>
using namespace std;
class complex
{
public:
complex();
complex(double a);
complex(double a, double b);
complex operator+(const complex & A)const;
complex operator-(const complex & A)const;
complex operator*(const complex & A)const;
complex operator/(const complex & A)const;
void display()const;
private:
double real; //复数的实部
double imag; //复数的虚部
};
complex::complex()
{
real = 0.0;
imag = 0.0;
}
complex::complex(double a)
{
real = a;
imag = 0.0;
}
complex::complex(double a, double b)
{
real = a;
imag = b;
}
//打印复数
void complex::display()const
{
cout<<real<<" + "<<imag<<" i ";
}
//重载加法操作符
complex complex::operator+(const complex & A)const
{
complex B;
B.real = real + A.real;
B.imag = imag + A.imag;
return B;
}
//重载减法操作符
complex complex::operator-(const complex & A)const
{
complex B;
B.real = real - A.real;
B.imag = imag - A.imag;
return B;
}
//重载乘法操作符
complex complex::operator*(const complex & A)const
{
complex B;
B.real = real * A.real - imag * A.imag;
B.imag = imag * A.real + real * A.imag;
return B;
}
//重载除法操作符
complex complex::operator/(const complex & A)const
{
complex B;
double square = A.real * A.real + A.imag * A.imag;
B.real = (real * A.real + imag * A.imag)/square;
B.imag = (imag * A.real - real * A.imag)/square;
return B;
}
int main()
{
complex c1(1, 2);
complex c2(3, 4);
complex c3;
complex c4;

//复数的加法
c3 = c1 + c2;
cout<<"c3=c1 + c2 = ";
c3.display();
cout<<endl;

//复数的减法
c3 = c1 - c2;
cout<<"c3=c1 - c2 = ";
c3.display();
cout<<endl;

//复数的乘法
c3 = c1 * c2;
cout<<"c3=c1 * c2 = ";
c3.display();
cout<<endl;

//复数的除法
c3 = c1 / c2;
cout<<"c3=c1 / c2 = ";
c3.display();
cout<<endl;

c4 = c1 + c2 * c3;



cout<<"c1 + c2 * c3 = ";
c4.display();
cout<<endl;

return 0;
}
c3=c1 + c2 = 4 + 6 i 
c3=c1 - c2 = -2 + -2 i
c3=c1 * c2 = -5 + 10 i
c3=c1 / c2 = 0.44 + 0.08 i
c1 + c2 * c3 = 2 + 4 i