运算符重载的方法是定义一个重载运算符的函数,在需要执行被重载的运算符时,系统自动调用该函数,以实现相应的运算。运算符重载实质是函数的重载
重载运算符的函数格式如下:
函数类型 operator 运算符名称(形参列表)
{对运算符的重载处理}
例1 重载运算符“+”,使之能用于两个复数相加
#include "stdafx.h"
#include<iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(double r,double i){real=r;imag=i;}
Complex Complex::operator+(Complex &c2);
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(Complex &c2) // 定义重载运算符+的函数
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Complex c1(1,3),c2(7,-6),c3;
c3=c1+c2;
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c3=";c3.display();
return 0;
}
也可将运算符重载函数作为友元函数
#include "stdafx.h"
#include<iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(double r,double i){real=r;imag=i;}
friend Complex operator+(Complex &c1,Complex &c2);
void display();
private:
double real;
double imag;
};
Complex operator+(Complex &c1,Complex &c2)
{
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Complex c1(1,3),c2(7,-6),c3;
c3=c1+c2;
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c3=";c3.display();
return 0;
}