概述
转载请注明出处: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");
}
最后
以上就是奋斗小猫咪为你收集整理的C++学习笔记22,普通函数重载(1)的全部内容,希望文章能够帮你解决C++学习笔记22,普通函数重载(1)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复