我想从另一个cpp文件中获取一个值
例如这个在 fileone.cpp 中:
for (int i = 0; i < NSIZE(facerects); i++)
{
DetPar detpar;
detpar.x = facerect->x + facerect->width / 2.;
*gX=facerect->x;
detpar.y = facerect->y + facerect->height / 2.;
*gY=facerect->y;
}
我想获取 file2.cpp 中 *gX , *gY 的值
在 Java 中,我们可以使用 getters= 做到这一点,但在 C++ 中,最简单的方法是什么?
最佳答案
如果全局变量定义在另一个文件中,您可以使用extern
公开它们。
例如,如果在 file2.cpp 中有如下声明的变量:
int *gX; // a pointer to an integer
int *gY;
然后在 main.cpp 中,您可以使用 extern
来使用变量:
// define these near the top of your cpp file and then use them wherever you need to
extern int *gX; // a pointer to an integer defined elsewhere in your program
extern int *gY;
但是,如果您要按照源代码中的方式使用它们,至少要注意指向有效内存。简单地使用 int
(不是指针)会更好。
此外,值得考虑使用全局变量的影响 SO discussion of global variables in C/C++
关于c++ - 使用在不同源文件中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16975039/