在 C++ 中使用“this”关键字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6779645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of "this" keyword in C++
提问by moteutsch
Possible Duplicate:
Is excessive use of this in C++ a code smell
When should you use the "this" keyword in C++?
Is there any reason to use this->
可能的重复:
在 C++ 中过度使用 this 是一种代码异味
什么时候应该在 C++ 中使用“this”关键字?
有什么理由使用这个->
In C++, is the keyword this
usually omitted? For example:
在 C++ 中,关键字this
通常被省略吗?例如:
Person::Person(int age) {
_age = age;
}
As opposed to:
与之相反:
Person::Person(int age) {
this->_age = age;
}
回答by orlp
Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:
是的,它不是必需的,通常被省略。但是,在范围中覆盖变量后,可能需要访问它们:
Person::Person() {
int age;
this->age = 1;
}
Also, this:
还有这个:
Person::Person(int _age) {
age = _age;
}
It is pretty bad style; if you need an initializer with the same name use this notation:
这是非常糟糕的风格;如果您需要同名的初始化程序,请使用以下符号:
Person::Person(int age) : age(age) {}
More info here: https://en.cppreference.com/w/cpp/language/initializer_list
更多信息:https: //en.cppreference.com/w/cpp/language/initializer_list
回答by Rich
It's programmer preference. Personally, I love using this
since it explicitly marks the object members. Of course the _
does the same thing (only when you follow the convention)
这是程序员的偏好。就个人而言,我喜欢使用,this
因为它明确地标记了对象成员。当然_
做同样的事情(只有当你遵循约定时)
回答by Muad'Dib
Either way works, but many places have coding standards in place that will guide the developer one way or the other. If such a policy is not in place, just follow your heart. One thing, though, it REALLY helps the readability of the code if you do use it. especially if you are not following a naming convention on class-level variable names.
无论哪种方式都有效,但许多地方都制定了编码标准,以一种或另一种方式指导开发人员。如果没有这样的政策,就跟着你的心走。但是,有一件事,如果您确实使用它,它确实有助于代码的可读性。特别是如果您没有遵循类级变量名称的命名约定。
回答by Alok Save
this
points to the object in whose member function it is reffered, so it is optional.
this
指向在其成员函数中引用它的对象,因此它是可选的。
回答by Chad
For the example case above, it is usually omitted, yes. However, either way is syntactically correct.
对于上面的示例案例,通常省略,是的。但是,无论哪种方式在语法上都是正确的。
回答by balki
Yes. unless, there is an ambiguity.
是的。除非,有歧义。