C++笔记14

运算符重载

C++预定义的运算符,只能用于基本数据类型的运算:整型、实型、字符型、逻辑型···
+、-、*、/、%&、~、!、|、=、<<、>>、!=···

在C++里,我们想进行两个复数的加减运算
想直接写:complex_a+complex_b 是会编译出错的

运算符重载的概念就是对C++里预定义的运算符赋予多重的含义,使之作用于不同类型的数据时导致不同类型的行为
运算符重载的实质就是函数重载
可以重载为普通函数,也可以重载为成员函数
把运算符的表达式转换成对运算符函数的调用
把运算符的操作数转换成运算符函数的参数
运算符被多次重载时,根据实参的类型决定调用哪个运算符函数

运算符重载的形式

exp.

返回值类型 operator 运算符(形参表)
{
···
}
class Complex
{
public:
double real,imag;
Complex(double r=0.0,double i=0.0):real(r),imag(i){}
Complex operator-(const Complex & c);
};
Complex operator+(const Complex & a,const Complex & b)
{
return Complex(a.real+b.real,a,imag+b.imag);//返回一个临时对象
}
Complex Complex::operator-(const Complex & c)
{
return Complex(real-c.real,imag-c,imag);//返回一个临时对象
}
int main()
{
Complex a(4,4),b(1,1),c;
c=a+b;//等价于c=operator+(a,b);
cout<<c.real<<","<<c.imag<<endl;
cout<<(a-b).real<<","<<(a-b).imag<<endl;//a-b等价于a.operator-(b)
return 0;
}
输出:
5,5
3,3

c=a+b等价于c=operator+(a,b)
a-b等价于a.operator-(b)

重载为成员函数时,参数个数为运算符数目减一
重载为普通函数时,参数个数为运算数目符

猜你喜欢

转载自www.cnblogs.com/AirBirdDD/p/12294516.html