我们可以在C++中删除一个变量的名称吗

Can we delete name of a variable in C++?

本文关键字:变量 一个 C++ 删除 我们      更新时间:2023-10-16

我想知道是否有可能,例如,我定义了int temp,然后稍后,我将temp定义为float

我的意思是,我想在.cpp文件中多次使用名称"temp"。这可能吗?如果可能的话,怎么做?

编辑:我的意思是在同一范围内。

否,不能在同一范围内声明两个同名变量。它们的作用域必须不同。

像这样:

int temp; // this is global
struct A
{
    int temp; // this is member variable, must be accessed through '.' operator
};
int f1()
{
    int temp; //local temp, though the global one may by accessed as ::temp
    ...
}
int f2()
{
    int temp; //local
    // a new scope starts here
    {
        int temp; //local, hides the outer temp
        ...
    }
    // another new scope, no variable of the previous block is visible here 
    {
        int temp; // another local, hides the outer temp
        ...
    }
}

在C++中没有删除变量名称的概念。然而,自动变量的生存期和可见性仅限于它们声明的范围

void foo()
{
    {
        int temp;
        ...
    }
    {
        float temp;
        ...
    }
}

.cpp文件中的不同类型和变量可以使用相同的名称。它甚至可以在同一功能内完成。唯一的要求是名称位于不同的作用域中。

void LegalExample() { 
  int temp = 42;
  if (...) {
    float temp;
    ...
  }
}
void IllegalExample() {
  int temp;
  float temp;
}

一般来说,在同一函数中声明同名变量被认为是不好的做法。它通常只会导致开发人员感到困惑,并且您真正认为需要两次相同命名变量的地方通常表明您需要两个单独的函数

我认为这是不可能的。您可以将两个名为temp的变量放在不同的命名空间中。

你也可以使用这样的匈牙利符号:

void foo()
{
    float fTemp;
    int iTemp;
}

您应该避免这种情况,因为变量应该只做一件事。即使随着时间的推移使用不同的作用域,您也可能会感到困惑。最好用不同的名称定义几个变量包,而不是重复使用一个。

想一想你想利用这个变量得到什么,并相应地命名它。

这取决于您的范围。您可以在某个范围内定义一次变量名。您不能更改该变量的类型。

但是您可以在其他作用域中使用相同的变量名,例如cpp文件中的其他方法。

相关文章: