在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(参数个数,类型或者顺序)必须不同。
下面有实例:
重载函数:
Mysquare
(
)
#include
<iostream>
using
namespace
std
;
int
Mysquare
(
int
i);
float
Mysquare
(
float
f);
float
Mysquare
(
int
i,
int
j);
int
main
()
{
int
i,j;
float
f;
cout
<<
"请输入i j f"
<<
endl;
cin
>>
i
>>
j
>>
f;
int
a;
a
=
Mysquare
(i);
float
b;
b
=
Mysquare
(f);
int
c;
c
=
Mysquare
(i,j);
cout
<<
a
<<
""
<<
endl
<<
b
<<
""
<<
endl
<<
c
<<
endl;
return
0
;
}
int
Mysquare
(
int
i)
{
return
i
*
i;
}
float
Mysquare
(
float
f) //重载函数1
{
return
f
*
f;
}
float
Mysquare
(
int
i,
int
j) //重载函数2
{
float
m;
m
=
i
*
i
+
j
*
j;
return
m;
}
重载函数:
max()
nclude
<
iostream
>
using
namespace
std
;
int
max
(
int
i1,
int
i2)
{
int
a;
a
=
i1
+
i2;
cout
<<
"this is two int paramenters a = "
<<
a
<<
endl;
return
0
;
}
int
max
(
int
j1,
int
j2,
int
j3)
{
int
b;
b
=
j1
+
j2
+
j3;
cout
<<
"this is three int paramenters b = "
<<
b
<<
endl;
return
0
;
}
double
max
(
double
m1,
double
m2)
{
double
c;
c
=
m1
+
m2;
cout
<<
"this is two double paramenters c = "
<<
c
<<
endl;
return
0
;
}
double
max
(
double
n1,
double
n2,
double
n3)
{
double
d;
d
=
n1
+
n2
+
n3;
cout
<<
"this is three double paramenters d = "
<<
d
<<
endl;
return
0
;
}
int
main
()
{
int
a
=
1
, b
=
2
, c
=
3
;
max
(a, b);
max
(a, b, c);
double
d
=
1.1
, e
=
2.2
, f
=
3.3
;
max
(d, e);
max
(d, e, f);
return
0
;
}