我应该在课程中使用“ this”吗? [英] Should I use `this` within a class?

查看:90
本文介绍了我应该在课程中使用“ this”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 this-> dataMember 或仅使用 dataMember ?什么是更好的风格?在性能上有什么区别吗?

Within a member function of a class in C++, does it make a difference, if I use this->dataMember or just dataMember? What is considered better style? Is there any performance difference?

(我不是在谈论局部变量与数据成员同名的情况,在这种情况下,您必须知识,请使用 this-> 进行区分。)

(I am not talking about the case where a local variable has the same name as the data member, in which case you must, to my knowledge, use this-> to distinguish between them.)

推荐答案

一般来说,这是当地惯例的问题。我见过的大多数
地方都没有使用 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.

这篇关于我应该在课程中使用“ this”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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