我应该对 C++ 中的成员变量和函数参数使用相同的名称吗?

2021-12-29 00:00:00 naming-conventions parameters c++

我想知道在 C++ 中为 成员变量 和函数 参数 使用相同的名称是否是一个好习惯.

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++.

我有 Java 背景,这很常见.我想知道在 C++ 中执行以下操作是否存在缺点(代码有效):

I come from a Java background, where this was common. I am wondering if in C++ there are drawbacks doing the following (the code works):

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

    private:
       PlayerState *state;
}

<小时>

感谢您的回答.据我了解,虽然它有效,但更好的做法是放置某种标记来区分成员变量和函数参数,例如:


Thank you for the answers. As I understand while it works, a better practice would be to put some kind of marker to differentiate member variable from function parameters like:

 _ or m_

在某些编辑器(如 Qt Designer)中,成员变量以不同的颜色显示.这就是为什么似乎没有必要添加任何前缀.

In some editors (like Qt Designer), member variables are shows in a different color. This is why it did not seem necessary to add any prefixes.

推荐答案

这是正确的,并且是标准所允许的.但更好的方法是对成员变量使用一些命名约定.例如,您可以为所有成员变量使用 m_ 前缀,然后任何人都可以推断出 m_state 是什么.增加了代码的可读性,避免了常见错误.

That is correct, and allowed by the Standard. But a better approach is to use some naming-convention for member variables. For example, you could use m_ prefix for all member variables, then anyone could infer what m_state is. It increases the readability of the code, and avoids common mistakes.

另外,如果m_state是成员,那么就不必在成员函数中写this->m_state = state,直接写<代码>m_state = 状态.在您当前的代码中,this-> 部分变得必要,否则 state = state 将成为自赋值.

Also, if m_state is the member, then you don't have to write this->m_state = state in the member function, you could just write m_state = state. In your current code, this-> part becomes necessary, without which state = state will become self-assignment.

相关文章