为什么我们使用"this"指针?

编程入门 行业动态 更新时间:2024-10-23 19:29:25
本文介绍了为什么我们使用"this"指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在此示例中,如果可以在对象的帮助下简单地调用类的成员函数,那么为什么需要使用"this"指针呢?

What is the need of ''this'' pointer in this example, if we can simply call the member function of the class with the help of objects then why we use ''this'' pointer?

#include <iostream> using namespace std; class MyClass { int i; public: void setI(int val) { this->i = val; } int getI() { return this->i; } } ; int main() { MyClass o; o.setI(100); cout << o.getI(); return 0; }

推荐答案

在您的示例中,您不需要this. 但是: In your example you dont need this. But: class CRect : protected RECT { public: CRect(RECT& rcinit){ CopyRect(this,&rcinit); } operator RECT& (){ return *this; } };

这是一个简单的示例,您需要this. 问候.

Is a simple example you need this. Regards.

我们有时使用this来消除变量之间的混淆. 例如: we use this to sometimes remove confusions between variables. for example : class MyClass { void foo(); int i; }; void MyClas::foo() { int i; i = i; // confused ? i = this->i; // less confused ? }

大多数时候,您不需要这样做.您只需要真正使用this来精确指定要使用的两个同名变量中的哪个:本地/参数1或类级别/实例1.在这种情况下,使用this会强制识别类级别的变量,缺少它会导致使用局部变量或参数变量. 如果没有名称冲突.那么您就不需要使用this,因为编译器会自动将其插入.但是,如果您这样做,那不是一个错误-不必要,不整洁并且有点学习者"-但这不是一个错误! :laugh: Most of the time, you don''t need to. You only really need to use this to specify exactly which of two identically named variables you mean: the local / parameter one, or the class level / instance one. When you have this situation, using this forces recognition of class level variable, lack of it infers use of the local or parameter variable. If there is no name conflict. then you don''t need to use this, as the compiler will automatically insert it. But if you do, it''s not an error - unnecessary, untidy and a bit "learner" - but not an error! :laugh:

更多推荐

为什么我们使用"this"指针?

本文发布于:2023-06-01 10:26:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/412958.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!