Should I use the same name for a member variable and a function parameter in C++?

前端 未结 9 1792
自闭症患者
自闭症患者 2020-12-08 03:08

I am wondering if it is a good practice to use the same name for both a member variable and a function parameter in C++.

I come from a Java backgro

相关标签:
9条回答
  • 2020-12-08 03:34

    Normally people just put an underscore after the variable or use shorter less descriptive var names for the function parameter.

    I personally do not like the same name thing because when reading it, it is easy to make mistakes.

    0 讨论(0)
  • 2020-12-08 03:36

    This is more a style issue than anything else. Most of the time, there's no issue: state is a very poor name for a variable or a value, as variables and values should be qualified nouns, e.g.:

    void setState( PlayerState* newState )
    {
        currentState = newState;
    }
    

    In theory, anyway. In practice, I've found it useful to use prefixes, along the lines of:

    class Player
    {
        PlayerState* myState;
    public:
        void setState( PlayerState* newState )
        {
            myState = newState;
        }
    };
    

    When reading the code, if the name starts with my, it's clearly a member variable (and if it starts with our, it's a static member variable).

    Note too that in the constructor, you can do things like:

    Player::Player( PlayerState* state )
        : state( state )
    {
    }
    

    I'm not sure what this does for readability, however:

    Player::Player( PlayerState* initialState )
        : myState( initialState )
    {
    }
    

    looks a lot clearer (but for simple data holders, the distinction might not be so significant).

    0 讨论(0)
  • 2020-12-08 03:38

    Do it this way:

    class Player
    {
        public:
        void setState(PlayerState *state)
        {
            this->m_state = state;
        }
    
        private:
           PlayerState *m_state;
    }
    

    You'll thank me some time later on. Haha.. (:

    The "m_" ("Member") prefix distinguish members from functions and other stuff. Very useful with stuff like intellisense (or any other IDE auto-suggestion).

    Also, mark m_state as const if you do not intend to change it later. Just in case.

    0 讨论(0)
  • 2020-12-08 03:41

    There is not really any difference between the C++ and Java, the only drawback is that you have to type this->state = state instead of state = arg.

    But your code is perfectly acceptable, it's more of styling than anything else.

    0 讨论(0)
  • 2020-12-08 03:45

    I would suggest you to follow some coding style convention. Personally I use the:

    class Player
    {
        public:
        void setState(PlayerState *state)
        {
            _state = state;
        }
    
        private:
           PlayerState* _state;
    }
    
    0 讨论(0)
  • 2020-12-08 03:45

    It's fine, in-fact it might even be good form, so long as it's only ever in your constructor.

    0 讨论(0)
提交回复
热议问题