繁体   English   中英

请帮助我了解在下面的代码中使用相同的命名空间

[英]Please help me understand the use of the same namespace in the code below

我使用 Code::Blocks 找到答案,它给了我 42,这意味着 B=4,A=2; 我明白为什么A=2,但我不知道为什么B=4,而不是5; C++ 中的代码如下:

#include <iostream>
using namespace std;

namespace S
{
   int A = 1;
}

namespace S
{
   int B = A + 2;
}

int main()
{
   S::A = S::A+1;

   {
      using namespace S;
      ++B;
   }

   cout << S::B << S::A;
}

这与命名空间无关。

A 和 B 是两个独立的独立变量。

在启动期间,您将 A 设置为 1,然后将 B 设置为 3(此时计算 A+2 的结果)。

然后在 A 中加一,得到 2。

B 没有以任何方式“链接”到 A,因此对 A 的分配不会影响 B。

然后将 B 增加到 4。

您对 B 执行的唯一步骤是:

int B = A + 2; //from this point B == 3 since 1 + 2 == 3;
...
++B; //now B == 4 because it was incremented by 1 (++ operator);

命名空间在这里无关,只有在引用它时才能影响 B(除非在这里使用引用或指针)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM