在这种情况下,静态 int 的值会发生变化吗?
Does the value of a static int change in this case
>我目前有一个头文件,其中包含多个头文件和源文件。头文件看起来像这样
File:External.h
#ifndef EXTERNAL_H
#define EXTERNAL_H
#include "memory"
static int pid=-1;
#endif // EXTERNAL_H
这是我当前场景的简化,只是为了检查我是否可能错了。现在假设我有两个类foo
和bar
。这是我注意到的行为。
#include "External.h"
void foo::someMethod()
{
pid =13; //Change the value of pid;
bar_ptr = new bar();
}
//bar constrcutor
#include "External.h"
bar::bar()
{
int a = pid; //The value of a is -1 wasnt it suppose to be 13
}
假设的值不是 13 吗,特别是因为它是静态类型的开放变量(不是结构或类)。
这是因为每个文件都包含标头,因此每个编译单元(大致是源文件)内部都有以下定义:
static int pid=-1;
因此,他们每个人都有自己的副本。
实际上,您应该执行以下操作:
外部.h
// The declaration, so that people can access it
extern int pid;
外部.c
// The actual implementation
int pid = -1;
相关文章:
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 在这种情况下,java对象是否可以调用本机函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 在这种情况下,我真的复制了字节还是复制了字符?
- 为什么在这种情况下,bool 类型的输出等于 0?
- 在这种情况下,如何传递成员函数而不是函数?
- 为什么在这种情况下递增阵列名称有效?
- 在这种情况下我应该使用哪种设计模式
- 为什么在这种情况下我需要 .template
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 我是否访问了已释放的内存,或者在这种情况下DrMemory报告不正确?
- 在这种情况下,"typename..."意味着什么?
- 为什么在这种情况下 x = 44?
- 在这种情况下是私有的吗?试图使操作员<<过载
- 在这种情况下,如何防止C++输出/控制台窗体关闭
- 为什么 lambda nullptr 取消引用在这种情况下有效?
- 为什么在这种情况下,前向声明不起作用?
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在这种情况下,为什么模板即时深度超过限制?
- 在这种情况下,静态 int 的值会发生变化吗?