重载原则
c语言回顾
c语言是不允许函数重名的,换句话说c语言不支持函数重载,所以如果你要打印整型的话,可能要写个print_int
;打印字符串可能要写个print_str
,非常不方便。
可以看到编译器直接报错了:
改写test.c
#include <stdio.h>
void print_int(int i){
printf("i=%d\n",i);
}
void print_float(float f)
{
printf("f=%.2f\n",f);
}
在main.cpp
中调用:
#include <iostream>
#include "test.c" //include不仅可以加载头文件,还可以加载.cd文件
int main(int argc, const char * argv[]) {
print_int(1);
print_float(3.1415);
return 0;
}
run
i=1
f=3.14
看到可以正常输出,但是如果我们还有double,char,string,long等类型怎么办呢?如果每种类型都要定义一个函数,这是很不友好事情,来看看我们在c++如何实现的吧!
先思考一个问题:c语言都不支持重载,那么c++是如何做到的呢?其实这都是编译器的功劳,重载的本质是编译器编译的时候对函数进行了重命名。
c++函数重载
#include <iostream>
using namespace std;
void print(int i)
{
cout<<"整型:"<<i<<endl;
}
//参数类型不同
void print(string str)
{
cout<<"字符串:"<<str<<endl;
}
//参数个数不同
void print(string str,int i)
{
cout<<"字符串:"<<str<<endl;
}
//参数顺序不同
void print(int i,string str)
{
cout<<"字符串:"<<str<<endl;
}
int main(int argc, const char * argv[]) {
print(1);
print("hello world");
return 0;
}
整型:1
字符串:hello world