头文件包含函数和类声明.这些只是声明函数的名称,返回类型和参数列表. .cpp文件包含这些函数的定义 – 即实际实现.如果您在其他文件中包含#include,则头文件对程序的其余部分可见,但实现细节隐藏在.cpp文件中.
.cpp文件中声明/定义的任何不在.h文件中的内容对程序的其余部分是不可见的,因此您可以在.cpp文件中定义内部变量,辅助函数等,这些实现细节不会是可见的.这个例子就是我下面的例子中的foo().
您程序的粗略草图如下所示:
在prog1.h:
#include // and whatever other libraries you need to include
#define ARRAY_SIZE 100 // and other defines
// Function declarations
// Read number from file, return int
void read_number(int array[ARRAY_SIZE][ARRAY_SIZE]);
char assign_char(int n);
void print_array(int array[ARRAY_SIZE][ARRAY_SIZE]);
void neighbor_check(int array[ARRAY_SIZE][ARRAY_SIZE]);
在prog1.cpp中:
// included headers, defines, and functions declared in prog1.h are visible
#include "prog1.h"
void read_number(int array[ARRAY_SIZE][ARRAY_SIZE]) {
// implementation here
}
char assign_char(int n) {
char c;
// implementation here
return c;
}
void print_array(int array[ARRAY_SIZE][ARRAY_SIZE]) {
// implementation here
}
void neighbor_check(int array[ARRAY_SIZE][ARRAY_SIZE]) {
// implementation here
}
// not visible to anything that #includes prog1.h
// since it is not declared in prog1.h
void foo() {
// implementation here
}
在prog1_test.cpp中:
// included headers, defines, and functions declared in prog1.h are visible
#include "prog1.h"
// any other includes needed by main()
int main() {
int array[ARRAY_SIZE][ARRAY_SIZE];
read_number(array);
for (int i = 0; i < ARRAY_SIZE; i++) {
for (int j = 0; j < ARRAY_SIZE; j++) {
assign_char(array[i][j]);
}
}
neighbor_check(array);
print_array(array);
return 0;
}