我才刚刚开始我的第一个C ++程序,并且在我学习的过程中几乎就是在学习。该程序应该具有3个不同的文件,一个头文件(prog1.h),一个prog1.cpp文件(不确定该术语的正确术语)和一个包含main:测试我们程序的测试文件(prog1_test.cpp )。
在这方面都没有寻求帮助(但是,我确定一旦遇到问题,我肯定会发布另一个问题),但认为您需要知道该程序应该做什么才能理解我的问题。我们的程序应该从文件中读取一些数字,并将这些数字放入2D数组中。然后应该为每个数字值分配字符,并打印当前数组和使用字符创建的“图片”。然后它将遍历数组,确保每个数字与其邻居的值相差不超过1,如果相差不超过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]);
在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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句