之前提到了函数重载,C++提供了运算符重载,赋予一些运算符新的含义。
现在给出一个类的例程:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real = 0;
imag = 0;
}
Complex(double r,double i)
{
real = r;
iamg = i;
}
void display();
Complex complex_add(Complex &c2)
private:
double real;
double imag;
}
Complex Complex::complex_add(Complex &c2)
{
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<endl;
}
为了实现“+”对复数的重载,需要引入运算符重载,方法是定义一个重载运算符的函数,使指定的运算符不仅能实现原有的功能,而且能实现在函数中制定的新功能。在使用被重载的运算符时,系统就自动调用该函数,以实现相应的功能,即运算符重载是通过定义函数实现的,运算符重载实质上是函数的重载。
格式如下:
函数类型+operator+运算符名称(形参表)
{
对运算符的重载处理
}
如果想实现上述功能呢个,需要写成:
Complex operator + (Complex& c1,Complex& c2);
不能重载的符号有:.,*,::,sizeof,?:
重载不能定义新的运算符,不能改变运算符运算对象的个数和优先级和结核性,必须和自定义类型的对象一起使用,参数至少有一个类对象,可以将其定义成友元函数,且形参表参数至少大于2