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

自古美人都是妖i 提交于 2019-12-29 08:15:13

问题


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

#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?


回答1:


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. 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, e.g. append an underscore like

class A{
    int Data_;

    void MethodA();
};


来源:https://stackoverflow.com/questions/30494407/declaring-a-local-variable-within-class-scope-with-same-name-as-a-class-attribut

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!