转载请注明出处: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");
}