C++之函数

1、默认参数

默认参数从右向左定义,匹配时从左向右。默认参数在函数声明时写,不能在在函数定义时再写一遍。

#include <iostream>

using namespace std;

void foo(int ,int = 5,int = 10);

void foo2(float s=3.14,float t=1.14){
	cout << s+t << endl;
}

int main(int argc,char** argv){
	foo(20,30,40);
	foo(20,30);
	foo(20);
	//foo();//error
	//foo(1,,2);//error

	foo2();
	return 0;
}

void foo(int i,int j,int k){
	cout << i << " " << j << " " << k << endl;
}

2、函数重载

函数重载是指可以使用不同个数的形参或不同类型的形参来定义一组实现相同功能的同名函数。函数重载的关键有一个,第一函数名一样,很简单,函数名不一样那就是两个完全不同的函数了;第二形参要不一样,与返回值等其它信息无关。

#include <iostream>
#include <math.h>

using namespace std;

int max(int a,int b){
	return a>b ? a : b;
}

double max(double a,double b){
	return a>b ? a : b;
}

void max(char a,char b){
	cout << (a>b ? a : b) << endl;
}

#if 0
/*error*/
char max(char a,char b){
	return a>b ? a : b;
}

/*error*/
static char max(char a,char b){
	return a>b ? a : b;
}
#endif

int main(int argc,char** argv){
	cout << max(12,20) << endl;
	cout << max(3.14,-3.14) << endl;
	max('a','b');

	return 0;
}

函数重载可以和函数默认参数混用,但容易产生二义性。比如下面三个函数:

int foo(int);

int foo(int,int=3);

int foo(int,int=3,int=4);

如果这样使用foo(1),编译器无法识别到高调用这三个函数里的哪个函数。


3、C++与C语言混用

在C++项目中定义C语言头文件有以下规范:

#ifndef __FUNC__

#define __FUNC__

#ifdef __cplusplus

extern "C"{

#endif


foo();

...


#ifdef __cplusplus

}

#endif

下面是一个示例,我们创建一个C语言的头文件和源文件,然后在C++主程序中调用,由于C++支持函数重载,所以C++编译函数后会对函数名作一些处理。如果我们使用g++编译C++文件,使用gcc编译C文件,那在C语言中定义的函数在C和C++中编译出来的结果是不一样的,链接的时候就会出问题。

所以我们要使用下面的规范,它表示在C++中编译C代码时,使用C语言的特性而不是C++的特性。

#ifndef __FUN_H__
#define __FUN_H__

#ifdef __cplusplus
extern "C"{
#endif

void foo();

#ifdef __cplusplus
}
#endif

#endif


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值