在类范围内声明一个与类属性同名的局部变量
在观察另一个人的代码时,我意识到在 A 类的方法中,他声明了一个与 A 类的属性同名的本地 int.例如:
While observing another person's code, i realized that within class A's method he declared a local int with the same name as an attribute of class A. For example:
//classA.h
class A{
int Data;
void MethodA();
};
//classA.cpp
//classA.cpp
#include "classA.h"
using namespace std;
void A::MethodA(){
int Data; //local variable has same name as class attribute
Data = 4;
//Rest of Code
}
我发现编译器会接受它而不返回错误很奇怪.在上述情况下,4是分配给本地Data还是A::Data,在更复杂的情况下会导致什么问题?
I found it weird that the compiler would accept it without returning an error. In the above case, would the 4 be assigned to the local Data or A::Data, and what problems could this cause in more complex situations?
推荐答案
局部变量会影响成员一(它的范围更窄).如果你只是写
The local variable will shadow the member one (it has the more narrow scope). If you just write
Data = 4;
您将分配给局部变量Data
.您仍然可以使用
you will assign to the local variable Data
. You can still access the member variable with
this->Data = 4;
这基本上就像
{
int data = 4;
{
int data = 2;
data++; // affects only the inner one
}
}
至于未来的问题:只要您和所有将使用您的代码的人都了解规则并且知道您是故意这样做的,就没有问题.如果您不打算故意这样做,请让您的编译器对此发出警告.
As for problems in the future: As long as you and everyone who will ever work with your code understands the rules and is aware that you did this on purpose there is no problem. If you do not intend to do such things on purpose, make your compiler warn about it.
但是,如果您遵循成员变量的命名方案,那肯定会更省钱,例如附加下划线,如
However, it would certainly be saver if you followed a naming scheme for member variables, e.g. append an underscore like
class A{
int Data_;
void MethodA();
};
相关文章