C++学习函数重载

本文探讨了C++中的函数重载,通过展示相同函数名但参数个数不同、参数类型或顺序不同的例子,说明如何实现重载。同时,文章也提及了返回值不同但参数相同的函数不能构成重载的情况。最后,通过`display`和`func`函数的实例展示了重载在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;

//函数名相同,参数个数不同
int sum(int v1, int v2) {
	return v1 + v2;
}
int sum(int v1, int v2, int v3) {
	return v1 + v2 +v3;
}

//函数名相同,参数类型或顺序不同
void func(int v1, double v2) {
	cout << "func(int v1, double v2)" << endl;

}
void func(double v1, int v2) {
	cout << "func(double v1, int v2)" << endl;
}

//返回值不同,参数相同,不能构成重载
//int func() {
//	return 0;
//}
//double func() {
//	return 0;
//}

void display() {
	cout << "display()-" << endl;
}
void display(int a) {
	cout << "display(int)-" << a << endl;
}
void display(long a) {
	cout << "display(int)-" << a << endl;
}
void display(double a) {
	cout << "display(int)-" << a << endl;
}

int main() {
	display();
	display(10);
	display(10L);
	display(10.0);

	/*func(10, 10.5);
	func(10.5, 10);

	cout << sum(10, 20) << endl;
	cout << sum(10, 20, 30) << endl;*/
	getchar();
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值