头文件function.h
源文件:main.cpp
#ifndef _FUNCTION_H_ //头文件嵌套,会出现函数被重复定义的问题,加上此可以保证头文件不会被定义多次
#define _FUNCTION_H_
//#pragma once //也可以使用此来防止多次的包含
/*
先声明一个函数,后面再定义(声明可以很多次,定义只能一次)
该函数的定义必须写在源文件中,不然若有多个文件include该头文
件时在链接是会报标识符重复的错误
*/
void my_fun(int, int);
void my_fun(int);
/*
或者写成内联函数,内联函数会直接将函数内容替换到调用的地方
就不会出现链接时标识符重复的错误
*/
inline void my_fun2()
{
//cout << "fun2" << endl;
}
/**************************************************
除了inline函数之外头文件中不能有任何形式的函数定义
***************************************************/
#endif
头文件:function2.h
#include "function.h"
源文件:main.cpp
#include <iostream> //<> 系统库中检索头文件
#include "function.h" //"" 在当前工程中检索,若不存在,则检索系统库中的头文件
using namespace std;
//编译的过程分为两步:编译和链接
//编译是将cpp文件编译生成obj文件
//链接是将目标文件(obj)以及所需的库文件彼此连接生成可以执行的文件(exe文件)
int main()
{
my_fun(1,2);
my_fun(1);//虽然my_fun(int,int)定义了默认参数,但是该函数还是调用my_fun(int)
my_fun2();
return 0;
}
#include "function.h"
#include "function2.h"
#include <iostream>
using std::cout;
using std::endl;
void doto()
{
my_fun(4,2);
my_fun2();
}
void my_fun(int a, int b=10) //默认参数只能是最后面的一个或者多个,如果是间隔出现,就不知道用哪些参数作为默认参数了
{
cout << __FUNCTION__ << "(int,int)" << endl;
}
void my_fun(int a)
{
cout << __FUNCTION__ << "(int)" << endl;
}
//返回值不作为函数的标识
//int my_fun(int a, int b)
//{
// cout << __FUNCTION__ << endl;
//}