![](/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.