//C++允许功能相近的函数在相同的作用域内以相同函数名声明,从而形成重载。方便使用,便于记忆。
//int add(int x, int y);
//float add(float x, float y); 形参类型不同
//int add(int x, int y);
//int add(int x, int y, int z); 形参个数不同
//重载函数的形参必须不同: 个数不同或类型不同。
//编译程序将根据实参和形参的类型及个数的最佳匹配来选择调用哪一个函数。
//1. 编译器不以形参名来区分;
//2. 编译器不以返回值来区分;
//3. 不要将不同功能的函数声明为重载函数,以免出现调用结果的误解、混淆。
#include<iostream.h>
struct complex
{
double real;
double imaginary;
};
int add(int m, int n)
{ return m+n; }
double add(double x, double y)
{ return x+y; }
complex add(complex c1, complex c2)
{
complex c;
c.real=c1.real+c2.real;
c.imaginary=c1.imaginary+c2.imaginary;
return c;
}
int main(void)
{
int m, n;
double x, y;
complex c1, c2, c3;
int add(int m, int n);
double add(double x, double y);
complex add(complex c1, complex c2);
cout<<"Enter two integer: ";
cin>>m>>n;
cout<<"integer "<<m<<'+'<<n<<"="<<add(m,n)<<endl;
cout<<"Enter two real number: ";
cin>>x>>y;
cout<<"real number "<<x<<'+'<<y<<"= "<<add(x,y)
<<endl;
cout<<"Enter the first complex number: ";
cin>>c1.real>>c1.imaginary;
cout<<"Enter the second complex number: ";
cin>>c2.real>>c2.imaginary;
c3=add(c1,c2);
cout<<"complex number (" <<c1.real<< ','
<< c1.imaginary <<")+("<<c2.real<<','
<<c2.imaginary<<")=("<<c3.real<<','
<<c3.imaginary<<")\n";
return 0;
}
C++学习笔记_6:函数的重载
最新推荐文章于 2023-03-14 20:07:30 发布