C++学习笔记22,普通函数重载(1)

转载请注明出处:http://blog.csdn.net/qq844352155/article/details/31353325
该博文仅用于交流学习,请慎用于任何商业用途,本博主保留对该博文的一切权利。
博主博客:http://blog.csdn.net/qq844352155

什么是方法重载?

方法重载也可以说是函数重载,函数的多态性。

具体来说就是将函数或者方法的名称用于多个函数,但是参数的类型或者参数的数目不同。

在这篇blog里面我只讨论类外函数的重载。

例如一个简单的例子:

#include <iostream>
#include <string>
using namespace std;

void printf(int i){
	cout<<"This is an int:"<<i<<endl;
}
void printf(const string s){
	cout<<"This is a string:"<<s<<endl;
}
int main(){
	int a=10;
	string s="my name is jack!";
	printf(a);
	printf(s);
	system("pause");
}
该cpp里面有两个同名的printf函数,但是两者的参数类型不同,这就是一个最简单的函数重载的例子。

当传递的参数不一样时,将调用对应的函数。


但是需要注意的是,有时候编译器会进行自动转换。

#include <iostream>
#include <string>
using namespace std;

void printf(const char i){
	cout<<"This is an char:"<<i<<endl;
}
void printf(const string s){
	cout<<"This is a string:"<<s<<endl;
}
int main(){
	int a=11;
	string s="my name is jack!";
	printf(a);
	printf(s);
	printf(67);
	system("pause");
}
运行结果:


可以看到,int自动转换为了char类型。

如果不希望自动转换,在C++11中支持删除指定重载函数的方法.

#include <iostream>  
#include <string>  
using namespace std;  
  
void printf(int i){  
    cout<<"This is an int:"<<i<<endl;  
}  
void printf(const string s){  
    cout<<"This is a string:"<<s<<endl;  
}  
void printf(char c)=delete;
int main(){  
    int a=10;  
    string s="my name is jack!";  
	char ch='a';
    printf(a);  
    printf(s); 
	 printf(ch); 
   
	return 0;
}  


这样就可以阻止自动转换了.

需要注意的是:一些看起来参数不一样的函数时不能共存的。例如

void printf(const string s){
	cout<<"This is a const string:"<<s<<endl;
}
void printf(string s){
	cout<<"This is a string:"<<s<<endl;
}
以及:

void printf(string &s){
	cout<<"This is a const string:"<<s<<endl;
}
void printf(string s){
	cout<<"This is a string:"<<s<<endl;
}

从编译器的角度去看printf(s);编译器根本不知道你究竟想要调用哪一个函数。

这些情况,编译器会认为是错误。

但是对于重载引用参数,这个有点不一样。例如

</pre><pre name="code" class="cpp">#include <iostream>
#include <string>
using namespace std;
void printf(const string &s){
	cout<<"This is a const string:"<<s<<endl;
}
void printf(string &s){
	cout<<"This is a string:"<<s<<endl;
}

int main(){
	string s="my name is jack!";
	printf(s);
	const string cs="hello world!";
	printf(cs);
	system("pause");
}

运行结果:


编译器将自动调用最匹配的那一个函数。

这个就是普通的函数重载,在类外的情况。

其实这个可以通过模板函数来代替,并且更加高效。

#include <iostream>
#include <string>
using namespace std;
template<class T>
void printf(T t){
	cout<<"I don't know what it is!but I can show it -->"<<t<<endl;
}

int main(){
	int a=10;
	string s="my name is jack!";
	printf(a);
	printf(s);
	system("pause");
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值