C++ primer 6.4函数重载

如果同一作用域内函数名相同但形参列表不同,称之为函数重载
在调用时编译器会根据传入的实参类型判段调用的是哪个函数
main函数不能被重载

#include<string>
#include <iostream>
using namespace std;
void print(int i) {
	cout << i << endl;
}
void print(string i) {
	cout << i << endl;
}
void print(int i, string j) {
	cout << i << "\n" << j << endl;
}
int main()
{
	print("hello");//编译器会根据传入的参数判读用哪种调用方式
	print(1);
	print(2, "hello");
	system("pause");
	return 0;
}

有时候两个形参看起来不一样实际上一样

void print(const int&);//此处省略了形参名
void print(const int& i);
//------------------------
typedef int Sun;//Sun是int的类型别名
void print(const Sun&);
void print(const int&);

一个有顶层const的形参无法和没有顶层const形参区分开
当传递一个非常量对象或者非常量指针,编译器会优先选用非常量版本的函数

void print(int);
void print( const int);//重复声明了void print(int)

void print(int*);
void print(int *const);//重复声明了 void print(int *)

如果形参是某种类型的指针或引用,则通过区分指向的是常量对象还是非常量对象来区分是否是重载

void print(string&);//函数作用于string的引用
void print(const string&);//新函数作用于常量引用
//编译器会推断传入的实参是否是常量,来调用哪个函数
//如果传入的是非常量的实参,编译器会优先调用,非常量的版本的函数

const_cast与重载

//此函数返回类型为const string的引用
const string& shorterString(const string& s1, const string& s2) {
	return s1.size() <= s2.size() ? s1 : s2;
}
//下面的函数使用了const_cast将上面传入的常量引用转化为普通引用使得这个函数可以将常量引用转换为普通引用
string& shorterString(string& s1, string& s2)
{
	auto& r = shorterString(const_cast<const string&>(s1), const_cast<const string&>(s2));
	return const_cast<string&>(r);
}

6.4节练习

(a) int calc(int, int);
	int calc(const int, const int);          // 合法,重复声明可以,重复定义不行
(b) int get();
	double get();                            // 不合法,仅返回值不同
(c) int *reset(int *);
	double *reset(double *);                 // 合法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值