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

前端 未结 9 1806
自闭症患者
自闭症患者 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: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).

提交回复
热议问题