在不同的块中C++变量

C++ variables in different block

本文关键字:C++ 变量      更新时间:2023-10-16
#include <iostream>
using std::cout;
using std::endl;
int a {1};
int main()
{
int a {2};
{
int a {3};
cout << ::a << endl;
cout << a << endl;
}
return 0;
}

第一个输出是1,它是在函数之前定义的 a 的值main()

那么有没有办法输出在内部块的函数main()中定义的第二个a呢? 谢谢!

那么有没有办法输出函数中定义的第二个amain()在内部块中?

a{2}a{3}都在块范围内

因此,a{3}阴影a{2}内部块中。

要输出a{2},您只需移动a{3}声明点

int a {2};
{
cout << ::a << endl;
cout << a << endl; // a{2} will be used here
// since a{3} is not defined here yet.
int a {3};
cout << a << endl; // a{3} will be used here
// since it's already defined at this point
}