自学内容网 自学内容网

大话C++:第13篇 this指针

1 this指针概述

this指针是C++中的一个特殊指针,它隐含在每一个非静态成员函数中,指向调用该函数的对象。这个指针提供了对调用对象自身的访问,使得在成员函数中能够访问对象的成员变量和其他成员函数。

this指针的语法格式

// this指针本身
this
// this指针的成员    
this->member_identifier

2 this指针指向调用对象

在类的成员函数中,this指针始终指向调用该函数的对象。通过this,成员函数可以访问和修改对象的所有公有、保护和私有成员。

#include <iostream>
#include <string>

class Person 
{
public:
    Person(const std::string& newName, int newAge) : name(newName), age(newAge) 
    {
    }

    // 使用this指针区分成员变量和参数
    void SetName(const std::string& newName) 
    {
        this->name = newName; // 'this->name' 指的是成员变量
    }

    std::string GetName() const
    {
        return this->name; // 'this->name' 指的是成员变量
    }

    void SetAge(int newAge) 
    {
        this->age = newAge;
    }

    int GetAge() const 
    {
        return this->age;
    }
    
private:
    std::string name;
    int age;    
};

int main() 
{
    Person person("Alice", 25);

    // 修改名字
    person.SetName("Bob");

    // 获取名字
    std::cout << "Person's name: " << person.GetName() << std::endl;

    return 0;
}

3 this指针区分同名变量

在C++中,当成员函数的参数与类的成员变量同名时,this指针非常有用,因为它可以帮助我们区分这两个同名实体。this指针指向调用对象,而参数是传递给函数的局部变量。通过使用this指针,我们可以明确地访问类的成员变量。

#include <iostream>
#include <string>

class Person 
{
public:
    Person(const std::string& name, int age) 
    {
        this->name = name;
        this->age = age;
    }

    // 使用this指针区分成员变量和参数
    void SetName(const std::string& name) 
    {
        this->name = name; // 'this->name' 指的是成员变量
    }

    std::string GetName() const
    {
        return this->name; // 'this->name' 指的是成员变量
    }

    void SetAge(int age) 
    {
        this->age = age;
    }

    int GetAge() const 
    {
        return this->age;
    }
    
private:
    std::string name;
    int age;    
};

int main() 
{
    Person person("Alice", 25);

    // 修改名字
    person.SetName("Bob");

    // 获取名字
    std::cout << "Person's name: " << person.GetName() << std::endl;

    return 0;
}

4 this指针注意事项

this指针使用时,需要注意以下事项:

  • this指针只在非静态成员函数中有效。静态成员函数不与任何特定对象关联,因此没有this指针。

  • this指针的类型是指向类本身的指针,通常是ClassName *const,表示它指向一个常量对象(即不能通过this指针修改对象本身)。

  • this指针的存储位置可能因编译器和平台的不同而有所不同,但通常存放在寄存器中以提高访问速度。


原文地址:https://blog.csdn.net/whccf/article/details/142486138

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!