首先说明,函数重载时,必须要不同的函数,参数个数或参数类型不同。
一.非成员函数的重载
#include<iostream>
using namespace std;
int mul(int a,int b);
double mul(double a,double b);
int main()
{int s1,s2;double s3,s4;cout<<"输入两个乘数:";cin>> s1>>s2;cout<<"answer="<<mul(s1,s2)<<endl;cout<<"继续输入:";cin>>s3>>s4;cout<<"answer="<<mul(s3,s4)<<endl;return 0;
}
int mul(int a,int b)
{return a*b;
}
double mul(double a,double b)
{return a*b;
}
运行结果:
输入两个乘数:1 2
answer=2
继续输入:1.1 2.2
answer=2.42
***成员函数重载***求两个复数的和
#include<iostream>
using namespace std;
class complex{private:double real,imag;public:complex();//无参构造函数complex(double r,double i);complex(double r);complex add(complex f);void print(); };
int main()
{complex k1(1.1,2.2),k2(2.2,3.3),k3(1.1),total1,total2,total3;total1=k1.add(k2);total2=k2.add(k3);total3=k3.add(k1);cout<<"total1=";total1.print();cout<<"total2=";total2.print();cout<<"total3=";total3.print();return 0;}
complex::complex()
{real=0;imag=0;
}
complex::complex(double r)
{real=r;
}
complex::complex(double r,double i)
{real=r;imag=i;
}
complex complex::add(complex f)
{complex temp;temp.real=real+f.real;temp.imag=imag+f.imag;return temp;
}
void complex::print()
{cout<<real;if(imag>0)cout<<"+"<<imag<<"i"<<endl;elsecout<<imag<<"i"<<endl;}
运行结果:
3.3+5.5i
3.3+3.3i
2.2+2.2i
在调用求和函数时,返回值为一个类对象,要理解this指针所指的对象。