Should I use the same name for a member variable and a function parameter in C++?(我应该对 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.
这篇关于我应该对 C++ 中的成员变量和函数参数使用相同的名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该对 C++ 中的成员变量和函数参数使用相同的名称吗?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01