前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >C++ this指针:用于在成员函数中指向调用该函数的对象

C++ this指针:用于在成员函数中指向调用该函数的对象

作者头像
很酷的站长
发布2023-08-25 12:51:13
发布2023-08-25 12:51:13
26000
代码可运行
举报
运行总次数:0
代码可运行

C++中this指针是一个指向当前对象的指针。在成员函数中,可以使用this指针来访问调用该函数的对象的成员变量和成员函数。

一、定义和使用this指针

this指针是在成员函数内部定义的一个常量指针。它存储了当前对象的地址,可以通过它访问当前对象的成员变量和成员函数。在成员函数内,无需显式地传入this指针,编译器会自动将当前对象的地址赋给this指针。

下面是一个使用this指针的例子:

代码语言:javascript
代码运行次数:0
复制
class Person {
public:
    void setName(const std::string& name) {
        this->name = name;
    }
    std::string getName() const {
        return this->name;
    }
private:
    std::string name;
};

Person person;
person.setName("Tom");
std::cout << person.getName() << std::endl; // 输出Tom

在setName函数内部,this指针被用来访问成员变量name。这里this->name等价于成员变量name。在getName函数内部,this指针被用来访问成员函数getName()。这里this->getName()等价于调用成员函数getName()。

二、作为返回值的this指针

this指针可以作为返回值返回。这种情况下,返回的是指向调用该函数的对象的指针。为了实现这个功能,需要将返回类型设置为类的引用或指针类型。下面是一个例子:

代码语言:javascript
代码运行次数:0
复制
class Person {
public:
    Person& setName(const std::string& name) {
        this->name = name;
        return *this;
    }
    std::string getName() const {
        return this->name;
    }
private:
    std::string name;
};

Person person;
person.setName("Tom").setName("Jerry");
std::cout << person.getName() << std::endl; // 输出Jerry

在setName函数内部,返回的是指向调用该函数的对象的指针。这里使用了*this来访问调用该函数的对象。

三、作为函数参数的this指针

this指针也可以作为函数参数传递。这种情况下,可以在函数内部访问其他对象的成员变量和成员函数。下面是一个例子:

代码语言:javascript
代码运行次数:0
复制
class Person {
public:
    void setName(const std::string& name) {
        otherPerson.setName(name);
    }
    std::string getName() const {
        return this->name;
    }
private:
    std::string name;
    Person otherPerson;
};

Person person;
person.setName("Tom");
std::cout << person.getName() << std::endl; // 输出Tom
std::cout << person.otherPerson.getName() << std::endl; // 输出Tom

在setName函数内部,将传入的name参数设置到了otherPerson对象的name成员变量中。在getName函数内部,使用了this指针访问调用该函数的对象的成员变量name。

四、总结

this指针在C++中是一个非常重要的概念,可以用来访问调用该函数的对象,作为返回值返回,或者作为函数参数传递。掌握this指针的使用可以帮助我们更好地编写面向对象的程序。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、定义和使用this指针
  • 二、作为返回值的this指针
  • 三、作为函数参数的this指针
  • 四、总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档