通常使用相同的标识符(如变量名称)来表示同一范围内的另一个变量会产生编译器错误,是否有任何技术可以实际向编译器指示在此范围内直到此特定点此名称有其自己的目的并且是用于引用此变量,但在此之后,相同的名称将引用其他东西,例如另一个用于其他目的的变量?
问问题
1961 次
4 回答
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.
您可以使用指针,以便可以将其更改为指向不同的变量,但这不是您要问的,我怀疑。在任何情况下,除非您使用 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.
如果你的提议是这样的:
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;
我不确定我是否明白这一点。我认为您可以通过将定义放在新范围内(即大括号)来做到这一点:
{
float f = 3.141592653589;
// do something with f while it's PI
}
{
std::string f = "hello";
// do something with f while it's "hello"
}
但这并不是说我们在世界范围内都缺乏变量名。而且,如果您很好地命名变量,那么字符串和浮点数甚至不太可能具有相同的名称(可能是双精度和浮点数,但添加到语言中仍然是一个可疑的函数)。
于 2010-10-22T07:03:56.577 回答
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
}
}
于 2010-10-22T07:12:38.480 回答
0
当人们询问该语言极其晦涩的极端案例时,这很有趣。一个人怀疑一个家庭作业问题(提出问题的人几乎必须知道“答案”)。但无论如何,...
#include <iostream>
struct ouch { int x; };
void ouch( ouch ) { std::cout << "ouch!" << std::endl; }
int main()
{
struct ouch ah = {};
ouch( ah );
}
干杯&hth.,
于 2010-10-22T09:16:20.020 回答
0
void fn()
{
int a = 1;
#define a b
int a = 2;
}
但是......虽然尝试这个有点毫无意义,对吧?
于 2010-10-22T09:19:44.217 回答