C++ 之 this指针的使用

在 C++ 中,this 是一个指向当前对象的指针。当你在类的成员函数内部访问对象的成员变量或成员函数时,this 指针可以用来引用当前正在被调用的对象。

以下是 this 指针的主要用途和含义:

1. 引用成员变量:

在类的成员函数内部,可以使用 this-> 来引用对象的成员变量。

cpp 复制代码
class MyClass {
public:
    int myVar;

    void setVar(int var) {
        this->myVar = var;
    }
};

2. 返回对象自身:

在某些情况下,你可能需要在成员函数中返回对象自身的引用。使用 this 可以方便地实现这一功能。

cpp 复制代码
class MyClass {
public:
    int myVar;

    MyClass(int var) : myVar(var) {}

    MyClass& getSelf() {
        return *this;
    }
};

3. 解决命名冲突:

在成员函数参数名与成员变量名相同时,可以使用 this 指针来引用成员变量,以避免命名冲突。

cpp 复制代码
class MyClass {
public:
    int myVar;

    MyClass(int myVar) {
        this->myVar = myVar;
    }
};

注意事项:

  • this 指针只能在非静态成员函数内部使用,因为静态成员函数没有与任何特定对象实例相关联。
  • 在使用 this 指针之前,通常需要检查指针是否为空,以防止空指针解引用的错误。

总之,this 指针在 C++ 中用于引用当前正在被调用的对象,它是面向对象编程中的一个重要概念,帮助我们在类的成员函数内部访问和操作对象的成员变量和成员函数。

cpp 复制代码
#include <iostream>

class Person {
private:
    std::string name;
    int age;

public:
    // 构造函数
    Person(const std::string& name, int age) {
        this->name = name;
        this->age = age;
    }

    // 成员函数,设置姓名
    void setName(const std::string& name) {
        this->name = name;
    }

    // 成员函数,设置年龄
    void setAge(int age) {
        this->age = age;
    }

    // 成员函数,获取姓名
    std::string getName() const {
        return this->name;
    }

    // 成员函数,获取年龄
    int getAge() const {
        return this->age;
    }

    // 成员函数,显示个人信息
    void display() const {
        std::cout << "Name: " << this->name << ", Age: " << this->age << std::endl;
    }

    // 成员函数,返回对象自身的引用
    Person& getSelf() {
        return *this;
    }
};

int main() {
    // 创建 Person 对象
    Person person("Alice", 30);

    // 使用成员函数设置姓名和年龄
    person.setName("Bob");
    person.setAge(25);

    // 使用成员函数获取姓名和年龄,并显示个人信息
    std::cout << "Name: " << person.getName() << ", Age: " << person.getAge() << std::endl;
    person.display();

    // 返回对象自身的引用并显示个人信息
    Person& selfRef = person.getSelf();
    selfRef.display();

    return 0;
}
相关推荐
blasit3 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 天前
信号量和信号
linux·c++