只是想知道...
在使用 C++ 时,我发现如果您创建一个名为 circle
的类,然后声明一个与类名完全相同的变量,编译器不会报错。例如:
class circle {
// whatever it does in here
};
circle circle; // is a valid statement, but
circle *circle = new circle(); // gives you a 'circle' is not a type complain
事实证明,这适用于字符串 string = "string";以及。并尝试使用 Java,也可能。我猜它也可能适用于 C#,但我还没有尝试过。
谁能告诉我这背后的原因以及这是否是有意设计的功能?
最佳答案
n3337 9.1/2
A class declaration introduces the class name into the scope where it is declared and hides any class, variable, function, or other declaration of that name in an enclosing scope (3.3). If a class name is declared in a scope where a variable, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier (3.4.4).
n3337 9.1/4
[ Note: The declaration of a class name takes effect immediately after the identifier is seen in the class definition or elaborated-type-specifier. For example, class A * A; first specifies A to be the name of a class and then redefines it as the name of a pointer to an object of that class. This means that the elaborated form class A must be used to refer to the class. Such artistry with names can be confusing and is best avoided. —end note ]
所以。
class circle {
// whatever it does in here
};
int main()
{
circle *circle; // gives you a 'circle' is not a type complain
}
编译良好。
class circle {
// whatever it does in here
};
int main()
{
circle *circle = new class circle(); // gives you a 'circle' is not a type complain
}
编译也很好。
关于java - 使用对象标识符作为变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12392469/