1、什么是运算符的重载
重载:重新赋予新的含义;函数重载:对一个已有的函数赋予新的含义,使之实现新的功能。
运算符也可以重载,例:计算机处理整数、单精度数和双精度数进行加法的操作方法是不同的,由于C++已经对运算符“+”进行了重载,使“+”能适用于int,float,double类型的不同的运算。
例题1.通过函数来实现复数相加
#include<iostream>
using namespace std;
class Complex
{
private:
double real;//实部
double imag;//虚部
public:
Complex()
{
real=0;
imag=0;
}//定义构造函数
Complex(double r,double i)
{
real=r;
imag=i;
}//构造函数重载
Complex complex_add(Complex &c2)
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}//定义复数相加函数
void display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}//定义输出函数
};
int main()
{
Complex c1(3,4),c2(5,-10),c3;
c3=c1.complex_add(c2);
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c1+c2=";
c3.display();
return 0;
}
运算结果
c1=(3,4i)
c2=(5,-10i)
c1+c2=(8,-6i)
2.运算符重载的方法
运算符重载是定义一个重载运算符的函数,是指定的运算符不仅能实现原有的功能,而且能实现函数中指定的新功能。在使用被重载的运算符时,系统就自动调用该函数,以实现相应的功能。运算符重载的实质上是函数的重载。
重载运算符的函数一般格式如下: 函数类型 operator 运算符名称(形参表){ 对运算符的重载处理} Complex operator +(Complex &c1,Complex &c2); 在上面的一般格式下,operator是关键字,是专门用于定义重载运算符的函数,运算符名称就是C++已有的运算符。函数名是由operator和运算符组成。上面的“operator +”就是函数名,意思是“对运算符+重载的函数”。
例2:写出复数的所有运算符加减乘除,加加,减减的重载
#include<iostream>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex(){real=0;imag=0;}//无参构造函数初始化
Complex(double r,double i){real=r;imag=i;}//构造函数重载
Complex operator +(Complex &c2)//对"+"号的重载
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
Complex operator -(Complex &c2)//对"-"号的重载
{
Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
Complex operator *(Complex &c2)//对"*"号的重载
{
Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=real*c2.imag+imag*c2.real;
return c;
}
Complex operator /(Complex &c2)//对"/"号的重载
{
Complex c;
c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
void display();//定义输出函数
void set();
};
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
void Complex::set()
{
cout<<"input real=";
cin>>real;
cout<<" imge=";
cin>>imag;
}
int main()
{
Complex c1,c2,c3,c4,c5,c6;
c1.set();
c2.set();
c3=c1+c2;
c4=c1-c2;
c5=c1*c2;
c6=c1/c2;
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c1+c2=";c3.display();
cout<<"c1-c2=";c4.display();
cout<<"c1*c2=";c5.display();
cout<<"c1/c2=";c6.display();
return 0;
}
运行结果
input real=1
imge=2
input real=2
imge=2
c1=(1,2i)
c2=(2,2i)
c1+c2=(3,4i)
c1-c2=(-1,0i)
c1*c2=(-2,6i)
c1/c2=(0.75,0.25i)
摘自《C++程序设计》
谭浩强 编著