C ++中的静态全局变量 [英] Static global variables in C++

查看:155
本文介绍了C ++中的静态全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过malloc方法创建一个整数数组。我想这个数组是全球的,可以在我的程序中的任何地方使用。我把代码放在一个头文件,看起来像这样:

I would like to make an array of integers via the malloc method. I want this array to be global and be used anywhere in my program. I put code in a header file that looked like this:

static int *pieces;

然后我有一个函数,它填充了我想要的数字。该函数在命名空间中,命名空间在其自己的.cpp文件中实现。但是,我将头文件导入main.c并从创建数组的命名空间中调用函数,如:

Then I have a function that fills it with numbers that I want in there. The function is in a namespace and the namespace is implemented in its own .cpp file. However, I import the header file into main.c and call the function from the namespace that creates the array like:

pieces = malloc(sizeof(int) * 128);

但是当我尝试访问数组中的数字在main(在调用函数创建我的数组),它崩溃,并说,片断没有初始化。但在功能我有我可以创建它和操纵数字在它只是罚款。我的印象是,通过使一个静态变量,每当一个函数在任何地方改变(或设置它),那将影响变量在任何地方的使用。基本上我想说的是,为什么片段出现未设置在主,即使我设置在一个函数,我调用。

But when I try to access numbers in the array in main (after calling the function that creates my array), it crashes and says that pieces wasn't initialized. But in the function I have I can create it and manipulate the numbers in it just fine. I was under the impression that by making pieces a static variable, whenever some function anywhere changes (or sets it) then that will affect the usage of the variable anywhere. Basically what I'm trying to say is why does pieces appear unset in main, even though I set it in a function that I called?

推荐答案

静态是一种具有许多含义的关键字,在这种特殊情况下,意味着不是全局(释义)

Static is a keyword with many meanings, and in this particular case, it means not global (paraphrasing)

这意味着每个 .cpp 文件都有自己的副本。因此,当你在 main.cpp 中初始化时,它只在 main.cpp >。其他文件仍然未初始化。

It means that each .cpp file has its own copy of the variable. Thus, when you initialize in main.cpp, it is initialized ONLY in main.cpp. The other files have it still uninitialized.

解决这个问题的第一件事是删除关键字 static 。这将导致多重定义问题。为了解决这个问题,你应该在 .cpp 文件中定义变量,并在头文件中声明它。

First thing to fix this would be to remove the keyword static. That would cause the "Multiple definitions issue". To fix this you should define the variable in a .cpp file and just extern declare it in a header file.

编辑:你只是为它分配内存,不计为初始化

You are just allocating memory to it, doesnt count as initialization. You need to initialize the memory to 0 after allocation.

您可以改用 new int [128]()您的更详细的 malloc 语法,这会执行初始化好?或者,您可以采取容易的道路(这是它的有用),并使用 std :: vector

You can use new int[128]() instead of your more verbose malloc syntax, and this would perform initialization as well? Or you could take the easy road (thats what its there for) and use std::vector

这篇关于C ++中的静态全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆