函数重载 C++

在同一作用域中声明几个功能类似的同名函数,这些函数的形参列表不同(个数或类型)

cpp 复制代码
#include<iostream>
using namespace std;
// 1、参数类型不同
int Add(int left, int right)
{
 cout << "int Add(int left, int right)" << endl;
 return left + right;
}
double Add(double left, double right)
{
 cout << "double Add(double left, double right)" << endl;
 return left + right;
}
// 2、参数个数不同
void f()
{
 cout << "f()" << endl;
}
void f(int a)
{
 cout << "f(int a)" << endl;
}
// 3、参数类型顺序不同
void f(int a, char b)
{
 cout << "f(int a,char b)" << endl;
}
void f(char b, int a)
{
 cout << "f(char b, int a)" << endl;
}
int main()
{
 Add(10, 20);
 Add(10.1, 20.2);
 f();
 f(10);
 f(10, 'a');
 f('a', 10);
 return 0;
}
比

C++能够重载的原理:

名字修饰

C语言中没有名字修饰,而是在链接时直接用函数名取找地址,有同名函数时,区分不开。

C++中,在名字中引入参数类型等方法,区别了同名函数。

例如:在Linux环境下

cpp 复制代码
int Add(int left, int right);
//_Z3Addii 前面_Z是固定的,后面是函数名位数+函数名+参数类型
double Add(double left, double right)
//_Z3Adddd
相关推荐
QuZero几秒前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称7 分钟前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划
liulilittle16 分钟前
过冲:拥塞控制的呼吸与盲行
linux·网络·c++·tcp/ip·计算机网络·tcp·通信
Felven17 分钟前
B. Fair Numbers
数据结构·算法
人道领域21 分钟前
【LeetCode刷题日记】93.复原IP地址
java·开发语言·算法·leetcode
caimouse21 分钟前
Reactos 第 3 章 内存管理 — 【中篇】Hyperspace、系统空间、API 与异常
c语言·开发语言·windows·架构
jarreyer29 分钟前
【算法记录1】模型训练问题
算法
Felven31 分钟前
D. Friends and the Restaurant
算法
摇滚侠34 分钟前
JavaWeb 全套教程 Listener 112-113
java·开发语言·servlet·tomcat·intellij-idea
想吃火锅100534 分钟前
【leetcode】165.比较版本号js
javascript·算法·leetcode