通常在写工程中使用时,函数的声明放在头文件中,函数的定义放在具体的源文件中。原因有二:
-
避免声明和定义都在头文件中时,出现重定义的情况
实验文件:
头文件Chapter.h
#ifndef CHAPTER_H #define CHAPTER_H #include<iostream> using namespace std; int fact(int n); void fun1(int n) { cout << n << endl; return; } #endif
c++源文件a.cpp
#include"Chapter.h" #include<iostream> using namespace std; void fun2() { cout << "我是一个函数" << endl; }
b.cpp
#include"Chapter.h" #include<iostream> using namespace std; int main() { int n; cout << "请输入所需求解阶乘的数" << endl; cin >> n; cout << fact(n) << endl; return 0; } int fact(int n) { if (n == 1)return 1; return n * fact(n - 1); }
运行会报错:
说函数fun1重定义了,也就是a.cpp和b.cpp都引用了头文件Chapter.h,在同一个工程中,fun1被定义了两次。
解决方法:
-
可以参考fact函数,在头文件中声明,在cpp文件中定义
-
头文件中声明和定义函数的时候使用static,这样每个定义的函数都在自己的cpp中有效。
#ifndef CHAPTER_H #define CHAPTER_H #include<iostream> using namespace std; int fact(int n); static void fun1(int n) { cout << n << endl; return; } #endif
Q:同一个项目中,不同cpp文件定义头文件中声明的函数会怎么样
A:同样会出现重定义的情况,所以头文件中声明的函数,只需要在一个文件中定义即可。使用方法例如fact()和fact2()
#ifndef CHAPTER_H #define CHAPTER_H #include<iostream> using namespace std; int fact(int n); int fact2(int n); static void fun1(int n) { cout << n << endl; return; } #endif ------------------------------------- //a.cpp #include"Chapter.h" #include<iostream> using namespace std; int main() { int n; cout << "请输入所需求解阶乘的数" << endl; cin >> n; cout << fact(n) <<' ' <<fact2(n) << endl; return 0; } int fact(int n) { if (n == 1)return 1; return n * fact(n - 1); } ------------------------------------- //b.cpp #include"Chapter.h" #include<iostream> using namespace std; int fact2(int n) { return fact(n)+1; }
在b.cpp中能调用a.cpp中定义的fact(),而a.cpp中使用的fact2()可以在b.cpp中在定义,从这个例子中可以看出,在头文件中声明函数的好处。
所以:可以先在头文件中声明函数接口,然后在一个.cpp文件中对这些接口进行定义,然后其他文件使用这些函数。一方面有助于提前设计接口,也方便后期的维护。
Q:为什么不把函数的声明和定义都放在.cpp文件中
A:这样的话,不同的.cpp文件中重复使用的函数都需要反复声明,数量多了以后修改起来比较麻烦,在头文件中统一定义,修改起来方便。
注意:
函数在头文件中的声明格式:
void fun1(int a,double b);//正确 void fun1(int a,double b){};//错误,会报错,