我们可以在C++中删除一个变量的名称吗
Can we delete name of a variable in C++?
我想知道是否有可能,例如,我定义了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文件中的其他方法。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 用C++中的一个变量定义一个常量
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 全局变量 多读取器 一个写入器多线程安全?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 一个变量的输入值也会保存到另一个变量中
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 在另一个函数 (c++) 中调用变量
- 将双精度变量设置为另一个变量的值
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如果我注释掉换行符,为什么'string'会成为一个不合格的变量
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- C++使用cin给变量一个非整数的值
- 怎么可能有两个同名的变量——一个是全局变量,另一个是局部变量