什么是方法重载? 方法重载也可以说是函数重载,函数的多态性。 具体来说就是将函数或者方法的名称用于多个函数,但是参数的类型或者参数的数目不同。 在这篇blog里面我只讨论类外函数的重载。 例如一个简单的例子:
#include
#include
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
#include
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
#include
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);编译器根本不知道你究竟想要调用哪一个函数。 这些情况,编译器会认为是错误。 但是对于重载引用参数,这个有点不一样。例如
#include
#include
using namespace std;
void printf(const string &s){
cout<<"This is a const string:"<}
void printf(string &s){
cout<<"This is a string:"<}int main(){
string s=”my name is jack!”;
printf(s);
const string cs=”hello world!”;
printf(cs);
system(“pause”);
}运行结果:
编译器将自动调用最匹配的那一个函数。 这个就是普通的函数重载,在类外的情况。 其实这个可以通过模板函数来代替,并且更加高效。
#include
#include
using namespace std;
template
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”);
}
![]()
—————————————————————————————————————————————————— //写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。 转载请注明出处:https://www.royalchen.com/ author:royalchen Email:royalchen@royalchen.com ———————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/c学习笔记22,普通函数重载(1)/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!