C++函数声明与分离式编译

函数声明

函数的名字也必须在使用之前声明,类似于变量,函数只能定义一次,但可以声明多次。
函数声明无须函数体,用一个分号替代即可。因为不包含函数体,所以也就无须形参的名字。
函数三要素(返回类型、函数名、形参类型)描述了函数的接口,说明调用该函数所需的全部信息。函数声明也称作函数类型。
函数应该在头文件中声明而在源文件中定义。定义函数的源文件应该把含有函数声明的头文件包含进来。

分离式编译

分离式编译允许我们把程序分割到几个文件中去,每个文件独立编译。
编译和链接多个源文件:fact函数位于fact.cpp文件中,main函数位于main.cpp中,在head.h头文件中对这两个函数进行声明,在main函数中调用fact函数。

#ifndef HEAD_H
#define HEAD_H
int fact(int val);
int main();
#endif // HEAD_H
#include <iostream>
#include "head.h"
using namespace std;
//计算阶乘
int fact(int val)
{
    int ret = 1;
    while (val > 1){
        ret = ret * val;
        val = val - 1;
    }
    return ret;
}
#include <iostream>
#include "head.h"
using namespace std;

int main()
{
    int i;
    cout << "Please enter a number" << endl;
    cin >> i;
    int j = fact(i);
    cout << i << "! is : "<< j << endl;
    return 0;
}
发布了16 篇原创文章 · 获赞 11 · 访问量 642

猜你喜欢

转载自blog.csdn.net/qq_42820853/article/details/104587103