“这个”的使用C++ 中的关键字
可能的重复:
在 C++ 中过度使用此代码是否会产生代码异味
什么时候应该在 C++ 中使用“this”关键字?
有什么理由使用这个->
在 C++ 中,是关键字 this
通常被省略?例如:
Person::Person(int age) {
_age = age;
}
相对于:
Person::Person(int age) {
this->_age = age;
}
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->
In C++, is the keyword this
usually omitted? For example:
Person::Person(int age) {
_age = age;
}
As opposed to:
Person::Person(int age) {
this->_age = age;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,它不是必需的,并且通常被省略。不过,在变量在作用域中被覆盖后,可能需要访问变量:
此外,这:
这是非常糟糕的风格;如果您需要具有相同名称的初始值设定项,请使用此表示法:
更多信息请参见:https:// en.cppreference.com/w/cpp/language/initializer_list
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:
Also, this:
It is pretty bad style; if you need an initializer with the same name use this notation:
More info here: https://en.cppreference.com/w/cpp/language/initializer_list
这是程序员的偏好。就我个人而言,我喜欢使用
this
因为它明确标记了对象成员。当然_
做同样的事情(只有当你遵循约定时)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)无论哪种方式都有效,但许多地方都有适当的编码标准,可以以一种或另一种方式指导开发人员。如果这样的政策没有到位,那就随心所欲吧。但有一件事是,如果您确实使用它,它确实有助于代码的可读性。特别是如果您不遵循类级变量名称的命名约定。
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.
this
指向在其成员函数中引用它的对象,因此它是可选的。this
points to the object in whose member function it is reffered, so it is optional.是的。除非,有歧义。
Yes. unless, there is an ambiguity.
对于上面的例子,通常会被省略,是的。然而,无论哪种方式在语法上都是正确的。
For the example case above, it is usually omitted, yes. However, either way is syntactically correct.