我应该在C ++中为成员变量和函数参数使用相同的名称 [英] Should I use the same name for a member variable and a function parameter in C++
问题描述
我想知道,如果在C ++中为成员变量和函数参数使用相同的名称是一个好习惯。我来自Java背景,这是常见的。我想知道如果在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++. 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屋!