C++快速入门 第四十三讲:链接和作用域2

发布时间 2023-08-18 15:42:48作者: 一杯清酒邀明月
 1 header.h文件
 2 
 3 #ifndef HEADER_H
 4 #define HEADER_H
 5 
 6 unsigned long returnFactorial(unsigned short num);
 7 static const unsigned short headerNum = 5;//定义静态恒定值的全局变量 
 8 
 9 #endif
10 
11 that.cpp文件:
12 
13 #include "header.h"
14 unsigned short thatNum = 8;//定义全局变量 
15 bool printMe = true;//定义全局变量 
16 
17 unsigned long returnFactorial(unsigned short num)
18 {
19     unsigned long sum = 1;
20     
21     for(int i = 1;i<=num;i++)
22     {
23         sum *= i;
24     }
25     if(printMe)
26     {
27         return sum;
28     }
29     else
30     {
31         return 0;
32     }
33 }
34 
35 this.cpp文件:
36 
37 #include "header.h"
38 #include "iostream"
39 using namespace std;
40 extern unsigned short thatNum;//声明全局变量 
41 static bool printMe = false;//定义静态全局变量 
42 int main()
43 {
44     unsigned short thisNum = 10;
45     cout << thisNum << "! is equal to " << returnFactorial(thisNum) << "\n\n";
46     cout << thatNum << "! is equal to " << returnFactorial(thatNum) << "\n\n";
47     cout << headerNum << "! is equal to " << returnFactorial(headerNum) << "\n\n";
48     if(printMe)
49     {
50         cout << "小甲鱼真帅!\n\n";
51     }
52     return 0;
53 }