正确使用这个-> [英] Proper use of this->

查看:27
本文介绍了正确使用这个->的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类的 this 自引用的正确用法是什么?

What is the proper use of the this self-reference of a class?

我有时在方法中使用它来清除所使用的变量是成员变量而不是在方法中声明的变量,但另一方面,我想知道这是否是一个很好的理由,因为我认为您应该始终以一种不言自明的方式进行编码(和注释),因此会不必要地使用 this 并且反对它的另一个原因是您实际上生成了比需要更多的代码.

I sometimes use it inside a method to clear out that the variable used is a member variable and not one declared inside the method, but on the other side I am wondering if this is a good reason to do so, as I think you should always code (and comment) in a way which is self-explaining and therefore would make such an unneeded use of this unnecessary and another reason against it would be that you are actually producing more code than needed.

void function() {
  while(i != this->length) //length is member var
     /*do something*/
}

我经常遇到的另一种使用方法是在构造函数中(主要是在 Java 中),因为参数确实与必须初始化的成员变量具有相同的名称.正如 Primer 指出这是错误的代码,我我没有这样做,但另一方面,我看到如何使用与成员变量相同的名称作为参数名称清除它们的用途.

Another way of using it I frequently encounter is inside constructors (mostly in Java), as the parameters do have the same name as the member variables which has to be initialized. As the Primer states that this is bad code I am not doing this, but on the other side, I see how using the same name as the member-vars as parameter names clears out of which use they are.

C++
Constructor::Constructor(int size,int value) : this->size(size),
                                               this->value(value) {};

Java
Constructor(int size,int value) {
  this->size = size;
  this->value = value;
}

我希望实际上有一个规则考虑两种语言(Java/c++),如果没有,我将只为 c++ 重新标记,因为这是我更感兴趣的一种.

I hope there is actually a rule considering both languages (Java/c++), if not I will retag for just c++ as this is the one I am more interested in.

推荐答案

在大多数情况下,this-> 是多余的.例外情况是,如果你有一个同名的参数或局部变量(很容易,而且可能最好避免),或者在模板中,为了强制后面的符号是依赖的——在后一种使用中,这通常是不可避免的.

For the most part, this-> is redundant. The exception is if you have a parameter or a local variable of the same name (easily, and probably best avoided), or in a template, in order to force the following symbol to be dependent—in this latter use, it is often unavoidable.

这篇关于正确使用这个->的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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