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

前端 未结 1 1322
悲&欢浪女
悲&欢浪女 2020-12-20 05:17

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:

相关标签:
1条回答
  • 2020-12-20 05:42

    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();
    };
    
    0 讨论(0)
提交回复
热议问题