在范围内重用标识符的任何方法?

Poo*_*ria 2 c++ compiler-construction scope name-mangling

通常使用相同的标识符(如变量名称)作为同一范围内的另一个变量之类的东西会通过编译器生成错误.是否有任何技术实际向编译器指示在此范围内此特定点此名称有其自己的用途并且是用来引用这个变量,但是在这一点之后,同一个名称会引用另一个其他目的的另一个变量吗?

pax*_*blo 7

如果你的意思是变量,不,那就没有了.创建变量时,它与特定类型和特定位置相关联.话虽如此,没有什么可以阻止你为两个不同的东西重复使用相同的变量:

float f = 3.141592653589;
// do something with f while it's PI
f = 2.718281828459;
// now do something with f while it's E.
Run Code Online (Sandbox Code Playgroud)

您可以使用指针,以便可以将其更改为指向不同的变量,但这不是您所要求的,我怀疑.在任何情况下,除非你使用void指针并强制转换它,它仍然绑定到特定类型:

float pi = 3.141592653589;
float e  = 2.718281828459;
float *f = π
// do something with *f while it's PI
f = &e;
// now do something with *f while it's E.
Run Code Online (Sandbox Code Playgroud)

如果你提议的是:

float f = 3.141592653589;
// do something with f while it's PI
forget f;
std::string f = "hello";
// do something with f while it's "hello"
forget f;
Run Code Online (Sandbox Code Playgroud)

我不确定我是否明白这一点.我认为你可以通过将定义放在新范围内(即大括号)来做到这一点:

{
    float f = 3.141592653589;
    // do something with f while it's PI
}
{
    std::string f = "hello";
    // do something with f while it's "hello"
}
Run Code Online (Sandbox Code Playgroud)

但这并不是说我们的变量名称在世界范围内短缺.并且,如果你正好命名你的变量,那么字符串和浮点数甚至不太可能具有相同的名称(可能是double和float,但它仍然是添加到语言中的可疑函数).

  • +1回答和单词"世界范围内的变量名称短缺":) (5认同)
  • 我发现我不再需要宏了,内联函数和枚举是什么(我用过它们的唯一两件事),而且我的作用域已经非常安全,因为我的函数保持很小并且我的类遵循最小耦合,最大凝聚力原则. (2认同)

Ben*_*igt 5

好吧,你可以在函数中使用块,每个块都创建自己的范围.

void func(void)
{
   int a;
   {
      int b;
      // here a can be used and b is an int
   }
   {
      double b;
      // here a can still be used, but int b went out of scope
      // b is now a double and has no relationship to int b in the other block
   }
}
Run Code Online (Sandbox Code Playgroud)