#include<iostream>usingnamespace std;
voidsum(int a, int b){
cout << "void sum(int a, int b)" << endl;
}
voidsum(int a, int b, c){
cout << << endl;
}
{
(, );
(, , );
;
}
int
"void sum(int a, int b, int c)"
intmain()
sum
1
2
sum
1
2
3
return
0
参数顺序不同
参数类型相同,名字相同,但顺序不同也构成重载。
#include<iostream>usingnamespace std;
voidprocess(int a, double b){
cout << "void process(int a, double b)" << endl;
}
voidprocess(double a, int b){
cout << "void process(double a, int b)" << endl;
}
intmain(){
process(1, 1.1);
process(1.2, 1);
return0;
}
注意:函数重载与参数名字是否相同没有关系,只与类型有关。
C++ 支持函数重载的原因
C 语言不支持重载是因为同名函数无法区分。C++ 通过函数修饰规则来区分,只要参数不同,修饰出来的名字就不一样。在 Linux 环境下,使用 gcc 编译 C 文件,函数名修饰未发生改变;而使用 g++ 编译 C++ 文件,函数名修饰会改变,编译器将函数参数类型信息添加到了修改后的名字中。
#include<iostream>usingnamespace std;
intmain(){
int a = 0;
int& b = a;
int& c = b;
int& d = a;
cout << &a << endl;
cout << &b << endl;
cout << &c << endl;
cout << &d << endl;
b++;
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
d++;
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
return0;
}
使用场景
引用传递允许函数直接修改实参的值,避免值传递的拷贝开销(输出型参数)。
#include<iostream>usingnamespace std;
voidSwap(int* a, int* b){
int tmp = *a; *a = *b; *b = tmp;
}
voidSwap(int& a, int& b){
int tmp = a; a = b; b = tmp;
}
intmain(){
int x = 0, y = 1;
cout << x << " " << y << endl;
Swap(x, y);
cout << x << " " << y << endl;
return0;
}
函数重载、引用、内联函数、auto 和 nullptr 是 C++ 基础核心。重载让同名函数依参数适配场景;引用以别名简化操作、提升效率;内联平衡调用开销与复用;auto 减少类型声明冗余;nullptr 规范空指针。这些特性体现 C++ 在兼容与创新间的平衡,既承 C 语言高效,又添安全便捷。吃透并活用它们,是进阶高阶特性的基石,也能轻松应对面试基础考点,助你扎实迈入 C++ 之门。