你什么时候应该使用“this” C ++中的关键字? [英] When should you use the "this" keyword in C++?
问题描述
可能的重复项:
在C ++中过度使用这个代码气味
多年前,我习惯在访问成员变量时使用this->。我知道这不是绝对必要,但我认为更清楚。
Years ago, I got in the habit of using this-> when accessing member variables. I knew it wasn't strictly necessary, but I thought it was more clear.
然后,在某个时候,我开始更喜欢一个更简约的风格, ...
Then, at some point, I started to prefer a more minimalistic style and stopped this practice...
最近,我被一个更多的初级同学问我是否认为这是一个好主意,我发现我真的没有一个好的答案对于我的偏好...这是真的一个完全风格的选择,还是有真正的原因,为什么不加前缀 - >成员变量访问更好?
Recently I was asked by one of my more junior peers whether I thought it was a good idea and I found that I didn't really have a good answer for my preference... Is this really a wholly stylistic choice or are there real reasons why not prefixing this-> on member variable accesses is better?
推荐答案
虽然这是一个完全主观的问题,我认为一般的C ++社区喜欢不有 this->
。它是杂乱的,完全不需要。
While this is a totally subjective question, I think the general C++ community prefers not to have this->
. Its cluttering, and entirely not needed.
有些人使用它来区分成员变量和参数。一个更常见的做法是只使用一些下划线或 m
或 m _
等等。
Some people use it to differentiate between member variables and parameters. A much more common practice is to just prefix your member variables with something, like a single underscore or an m
, or m_
, etc.
在我看来,这更容易阅读。如果你需要 this->
来区分变量,你做错了。请更改参数名称(从 x
到 newX
)或具有成员变量命名约定。
That is much easier to read, in my opinion. If you need this->
to differentiate between variables, you're doing it wrong. Either change the parameter name (from x
to newX
) or have a member variable naming convention.
一致性是首选,因此您不需要为自己需要的少数案例强制 this->
区分(注意在初始化器列表中这是完全明确定义的: x(x)
,其中成员 x
通过参数 x
初始化),只是得到更好的变量名。
Consistency is preferred, so instead of forcing this->
on yourself for the few cases you need to differentiate (note in initializer lists this is completely well-defined: x(x)
, where the member x
is initialized by the parameter x
), just get better variable names.
c $ c> this :当我实际上需要实例的地址,无论什么原因。
This leaves the only time I use this
: when I actually need the address of the instance, for whatever reason.
这篇关于你什么时候应该使用“this” C ++中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!