我有一个头文件 abc.h
//abc.h
unsigned int *get(void)
{
static unsigned int input[] =
{
1,
2, 2,
4, 5,
6, 7
};
return input;
}
现在,我想将此输入(从头文件中,而不是从某些文本文件中)读入我的主 cpp 文件,例如 xyz.cpp
我正在考虑使用数组来访问这些元素,但我认为它不会起作用。
int arr[6];
arr=get();
第一个元素是测试用例的数量n,第二个和第三个元素是二维数组的维度,其余元素是二维数组的值。所以我需要输入n,rows的值,二维数组 arr[行][列]的列和值
关于如何实现这一目标有什么想法吗?
编辑:我真的不明白为什么这个问题被否决了。 我同意这不是一个好的实现,但是我已经获得了一个输入头文件,并且我只能通过这个头文件读取数据!!
最佳答案
如果您能够使用此文件编译您的程序,则无需读取任何内容。该数组及其值将被编译到您的程序中,您可以就地访问它们
您的 xyz.cpp 文件应如下所示:
#include "abc.h" // given abc file located in the same directory
int main(){
unsigned int * myArrayPtr = get();
// here comes some processing and, if you want, reading values from this array;
unsigned int numberOfCases = myArrayPtr[0];
unsigned int * dimensionsArrayPtr = myArrayPtr + 1;
unsigned int xArraySize = dimensionsArrayPtr[0];
unsigned int yArraySize = dimensionsArrayPtr[1];
// and etc.
// Most interesting part to represent those values as two dimensional array
// I left to you :)
return 0;
}
此外,您应该记住,此技巧仅在头文件中的数组声明为静态时才有效。否则你的程序将会有未定义的行为。
还有一个。如果您的函数体定义在头文件中,则应将其声明为内联。 只要此 header 仅包含在一个 cpp 文件中 - 就可以了。但是当它包含多个代码文件时,您将收到已定义链接器错误。
我建议你详细了解cpp中的指针。这篇文章够好了http://www.cplusplus.com/doc/tutorial/pointers/
关于 static 关键字 - 要完全理解这个例子 - SO 本身有很好的答案 The static keyword and its various uses in C++
关于c++ - 如何从头文件中读取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26483427/