我应该为C ++中的成员变量和函数参数使用相同的名称吗? [英] Should I use the same name for a member variable and a function parameter in C++?

查看:118
本文介绍了我应该为C ++中的成员变量和函数参数使用相同的名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于我应该为C ++中的成员变量和函数参数使用相同的名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆