我刚刚开始学习我的第一个C++程序,而且我正在学习.该程序应该有3个不同的文件,一个头文件(prog1.h),一个prog1.cpp文件(不确定这个文件的正确术语)和一个包含main的测试文件:测试我们的程序(prog1_test.cpp) ).
没有要求任何帮助(但是,我确定一旦我进入它就会发布另一个问题),但是你想知道你应该知道程序应该做什么才能理解我的问题.我们的程序应该从文件中读取一些数字并将这些数字放入2D数组中.然后应该为每个数字值分配字符并打印当前数组和用字符创建的"图片".然后它将遍历数组,确保每个数字的值与其邻居的值不超过1,如果是,则程序将用其相邻值的平均值替换该数字.然后程序将打印出这个校正的数组和用分配给校正数组的字符创建的"图片".
我知道头文件应该包含将在多个文件中使用的代码,但我很难弄清楚我的程序的哪些部分需要在这个文件中.例如,我的代码打开,读取和关闭数据文件是否包括在这里,或者没有,因为文件只被打开,读取和关闭一次?
头文件包含函数和类声明.这些只是声明函数的名称,返回类型和参数列表..cpp文件包含这些函数的定义 - 即实际实现.如果#include在其他文件中,头文件对于程序的其余部分是可见的,但实现细节隐藏在.cpp文件中.
.cpp文件中声明/定义的任何不在.h文件中的内容对程序的其余部分是不可见的,因此您可以在.cpp文件中定义内部变量,辅助函数等,这些实现细节不会是可见的.以下是foo()我的示例中的一个示例.
您程序的粗略草图如下所示:
在prog1.h:
#include <iostream> // 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]);
Run Code Online (Sandbox Code Playgroud)
在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
}
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2157 次 |
| 最近记录: |