简体   繁体   English

在类范围内声明与类属性同名的局部变量

[英]Declaring a local variable within class scope with same name as a class attribute

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: 在观察另一个人的代码时,我意识到在A类的方法中,他声明了一个本地int,其名称与A类的属性相同。例如:

//classA.h //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
}

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? 在上述情况下,将4分配给本地Data还是A :: Data,这在更复杂的情况下会引起什么问题?

The local variable will shadow the member one (it has the more narrow scope). 局部变量将阴影成员一(它的作用域更狭窄)。 If you just write 如果你只是写

Data = 4;

you will assign to the local variable Data . 您将分配给局部变量Data You can still access the member variable with 您仍然可以使用以下命令访问成员变量

this->Data = 4;

This works basically just as 基本上就像

{
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, eg append an underscore like 但是,如果您遵循成员变量的命名方案(例如,添加下划线,例如

class A{
    int Data_;

    void MethodA();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM