1、多态性:多态就是指不同对象收到相同的消息时会执行不同的操作,从而得到不同的结果,即所谓的“一个接口,多种实现”。
2、运算符的重载在代码实现中起到十分重要的作用,它可以提高代码的实现效率,省去很多重复的操作。重载的运算符可以实现多种不同的数据类型的操作。
3、运算符重载的限定词为“operator”,其运用为(以“+”为例):
int operator +(int ,int);//重载"+"实现两个int 类型的数据的相加,并返回int类型
double operator +(double ,double);//
重载"+"实现两个double 类型的数据的相加,并返回double类型
int operator +(int ,double);//重载"+"实现int和double不同类型的数据的相加,并返回int类型
如上所述,还有多种组合方式。
4、重载"+"实现两个复数的相加,代码如下:
/*********对“+”进行重载******/
/*********类外的运算符重载**/
#include<iostream>
using namespace std;
struct complex
{
double real,imag;
complex(double r=0,double i=0):real(r),imag(i) {}
void display()/****考虑运算后的结果虚部有三种情况***/
{
if(imag==0)
{
cout<<real<<endl;
}
else if(imag<0)
{
cout<<real<<imag<<"i"<<endl;
}
else
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
}
};
complex operator + (complex c1,complex c2)
{
complex t;
t.real=c1.real+c2.real;
t.imag=c1.imag+c2.imag;
return t;
}
/****主函数检验*****/
int main()
{
complex c1(2,6),c2(7,-4),c3;
complex c4(2,6),c5(7,-6),c6;
complex c7(2,6),c8(7,-8),c9;
c3=c1+c2;
c6=c4+c5;
c9=c7+c8;
cout<<"重载运算的结果为:\n";
c3.display();
c6.display();
c9.display();
return 0;
}
5、程序运行截图: