#include<iostream>
using namespace std;
void print(int a) {
cout << a << endl;
}
void print(double d) {
cout << d << endl;
}
void print(string s) {
cout << s << endl;
}
int main() {
print(10);
print(10.1);
print("C++");
return 0;
}
在上面的代码,可以看到我们对print函数进行了3个重载,分别传入不同数据类型的参数: int double string ,在下面main函数中,我们对print函数传入不同数据类型的参数,编译器会自动匹配出最适合的print函数进行调用,输出结果如下:
10
10.1
C++
我们知道,函数是有作用域的,就像变量,有局部变量和全局变量一样。如果一个变量在外部做了声明,在内部也做了声明,当我们在内部访问这个变量时,内部声明的变量会覆盖掉外部的变量。
#include<iostream>
using namespace std;
int a = 10; //全局变量
void func1() {
int a = 1; //局部变量
cout << a << endl;
}
void func2() {
cout << a << endl;
}
int main() {
func1(); //输出:1
func2(); //输出:10
return 0;
}
当然,函数也是类似的:
#include<iostream>
using namespace std;
void print(int a) {
cout << a << endl;
}
void print(double d) {
cout << d << endl;
}
void print(string s) {
cout << s << endl;
}
int main() {
void print(int); //内层对函数的声明,此时会覆盖掉外部其他重载函数
print(10.1); //此时会调用print(int)的函数,输出:10
// print("学习"); 这行代码会报错,因为print(string)已经被覆盖了
return 0;
}
1614

被折叠的 条评论
为什么被折叠?



