Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c++ - 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:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...