函数重载 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
相关推荐
Wild_Pointer.2 分钟前
Qt Creator:避免QRunnable和QObject多重继承
开发语言·qt
三无少女指南2 分钟前
关于JVM调优,我想聊聊数据和耐心
java·开发语言·jvm
Lei_3359674 分钟前
[算法]十大排序
数据结构·算法·排序算法
m0_7482402516 分钟前
C++仿Muduo库Server服务器模块实现 基于Reactor模式的高性
服务器·c++·php
大数据张老师31 分钟前
数据结构——堆排序
数据结构·算法·排序算法
南棱笑笑生40 分钟前
20251027在Ubuntu20.04.6上编译AIO-3576Q38开发板的Buildroot系统解决qt5webengine编译异常的问题
开发语言·qt·rockchip
沅霖44 分钟前
android kotlin语言中的协程
android·开发语言·kotlin
画个逗号给明天"44 分钟前
C++十大排序算法
数据结构·c++·排序算法
xiaobobo33301 小时前
c语言中const关键字和枚举enum的新认识
c语言·开发语言·const·enum
仰泳的熊猫1 小时前
LeetCode:268. 丢失的数字
数据结构·c++·算法·leetcode