我想從書中學習C++ Accelerated C++。在第一章結尾處有一個讓我感到沮喪的練習。從本質上講,我很奇怪,爲什麼下面的代碼編譯和運行完美:爲什麼我的C++代碼甚至用雙重聲明的變量編譯?
#include <iostream>
#include <string>
int main() {
{
const std::string s = "a string";
std::cout << s << std::endl;
{
std::cout << s << std::endl;
const std::string s = "another string";
std::cout << s << std::endl;
};
}
return 0;
}
在我看來,我倍加聲明字符串s,從我的理解,這是非法的。你能幫助我更好地理解這一點嗎?謝謝。生成的輸出是:
a string
a string
another string
強相關/可能重複:https://stackoverflow.com/questions/4151203/why-is-this-c-working-variables-with-the-same-name –