更新时间:2022-06-25 18:33:51
一般来说,这是当地惯例的问题。我见过的大多数
地方都没有使用 this->
,除非有必要,这也是我更喜欢的约定
,但是我听说有人更喜欢
系统地使用它。
As a general rule, it's a question of local conventions. Most of the
places I've seen do not use this->
except when necessary, and that's
the convention I prefer as well, but I've heard of people who prefer to
use it systematically.
有两种情况是有必要的。首先是您是否在本地范围内隐藏了
相同名称的名称;如果例如您有一个名为 toto
的成员
,并且您还将函数自变量 toto
命名为。许多
编码约定都标记了成员或修饰符来避免这种
的情况,例如所有成员名称都以 my
或 m _
开头,或者参数名称
的开头为 the
。
There are two cases when it is necessary. The first is if you've hidden
the name with the same name in local scope; if e.g. you have a member
named toto
, and you also named your function argument toto
. Many
coding conventions mark either the member or argments to avoid this
case, e.g. all member names start with my
or m_
, or a parameter name
will start with the
.
另一种情况是 this->
可以是在模板中使用,以使名称
依赖。如果模板类从
依赖类型继承而来,并且您想访问基类的成员,则这是相关的,例如:
The other case is that this->
can be used in a template to make a name
dependent. This is relevant if a template class inherits from a
dependent type, and you want to access a member of the base, e.g.:
template <typename T>
class Toto : public T
{
public:
int f()
{
return this->g();
}
};
此处没有 this->
, g()
是一个非依赖名称,
编译器会在模板定义
的上下文中查找它,而无需使用基础类。
Without the this->
here, g()
would be a non-dependent name, and the
compiler would look it up in the context of the template definition,
without taking the base class into consideration.