[英]C++ Static variable inside function cannot be changes
有人可以向我解釋以下內容嗎?
static_outer
按預期工作。 當調用print_str()
function 時, static_outer
被賦值給參數,然后打印到 output。
static_inner
“行為不端”。 當調用 function 時,它也會從參數中賦值。 但是第二次調用function時,打印出來的值和第一次調用時一樣。
為什么賦值不改變值? 我唯一的直覺是該行被忽略,因為static_inner
已經聲明但編譯器沒有抱怨。
static const char* static_outer;
void print_str(const char* const str) {
static const char* static_inner = str;
cout << static_inner << "\r\n";
static_outer = str;
cout << static_outer << "\r\n";
}
int main() {
const char str1[] = "Foo";
const char str2[] = "Bar";
cout << "First call" << "\r\n";
print_str(str1);
cout << "\r\n" << "Second call" << "\r\n";
print_str(str2);
}
// Output:
// First call
// Foo
// Foo
//
// Second call
// Foo <--- this is the line in question... why not "Bar"?
// Bar
初始化 function static 變量后,行static const char* static_inner = str;
沒有進一步的影響。
如果您希望變量在每次調用時都發生變化,則需要一行代碼執行賦值:
void print_str(const char* const str) {
static const char* static_inner;
static_inner = str;
cout << static_inner << "\r\n";
static_outer = str;
cout << static_outer << "\r\n";
}
我唯一的直覺是該行被忽略,因為
static_inner
已經聲明
你的直覺是正確的。 這正是發生的事情。 您在其聲明中將str
參數分配給static_inner
。 一個 static 局部變量只被初始化一次,function 第一次被調用。 在后續調用中,該變量保留其先前的值。
要做你想做的事,你需要將 static 局部變量的聲明與其賦值分開:
static const char* static_inner;
static_inner = str;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.