![](/img/trans.png)
[英]Manipulate a local static pointer variable outside the function where it is defined
[英]Global static variable not “staying defined” outside of function
我有一个程序,其中我全局定义的静态变量一旦离开我的“初始化函数”(不是构造函数)就不会保持初始化状态。 这是该计划:
type.h
namespace type
{
static int * specialInt;
}
type.cpp
#include "type.h"
(故意留空)
Branch.h
#include "type.h"
namespace type
{
bool initInt();
}
Branch.cpp
#include "Branch.h"
#include <iostream>
namespace type
{
bool initInt()
{
specialInt = new int;
*specialInt = 95;
std::cout << "Address from initInt(): " << specialInt << std::endl;
return true;
}
}
Leaf.h
#include "Branch.h"
#include <iostream>
namespace type
{
void PrintInt();
}
Leaf.cpp
#include "Leaf.h"
namespace type
{
void PrintInt()
{
std::cout << "Address: " << specialInt << std::endl;
std::cout << "Value: " << *specialInt << std::endl;
}
}
main.cpp中
#include "Leaf.h"
int main()
{
type::initInt();
type::PrintInt();
return 0;
}
输出是
来自initInt()的地址:007F5910
地址:00000000
在它崩溃之前。 我读到关键字static
让变量有外部链接,为什么这会失败? 为什么变量在initInt()
之外变得不定义?
namespace type
{
static int * specialInt;
}
这是静态整数指针的定义 。 命名空间范围内的static
请求内部链接:包含type.h
每个翻译单元都有自己独立的specialInt
版本。 然后,当然,对其中一个specialInt
的更改不会影响其他的。
你要做的是在type.h
声明变量:
namespace type
{
extern int * specialInt;
}
......并在其中一个翻译单元中提供单一定义:
#include "type.h"
int *type::specialInt;
然后,每个人都可以通过type.h
找到并使用该定义。
我读到关键字
static
让变量有外部链接,
不,当static与命名空间范围内的对象一起使用时,它指定内部链接。 这意味着, specialInt
分配的Branch.cpp
和specialInt
打印的Leaf.cpp
不是同一个对象。
3)...当在命名空间范围内的声明中使用时,它指定内部链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.