什么是“这个”的目的是什么,指针在C ++? [英] What is purpose of a "this" pointer in C++?

查看:188
本文介绍了什么是“这个”的目的是什么,指针在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关键字的目的是什么?类中的方法不能访问同一类中的其他对等成员吗?需要调用 this 来调用类中的对等方法吗?

What is purpose of this keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this to call peer methods inside a class?

推荐答案

两个主要用途:


  1. 要传递 * this 作为其他非类方法的参数。

  1. To pass *this or this as a parameter to other, non-class methods.

void do_something_to_a_foo(Foo *foo_instance);


void Foo::DoSomething()
{
    do_something_to_a_foo(this);
}


  • 允许删除成员变量和函数参数之间的歧义。这在构造函数中很常见。

  • To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.

    MessageBox::MessageBox(const string& message)
    {
      this->message = message;
    }


    (虽然初始化列表通常优先于此特定示例中的分配。)


  • (Although an initialization list is usually preferable to assignment in this particular example.)

    这篇关于什么是“这个”的目的是什么,指针在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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