C++ this指针(八股总结)

定义

this 指针是一个隐含于每一个非静态成员函数中的特殊指针。它指向调用该成员函数的那个对象。

当对一个对象调用成员函数时,编译程序先将对象的地址赋给 this 指针,然后调用成员函数,每次成员函数存取数据成员时,都隐式使用 this 指针。

作用

1.解决成员变量与函数参数同名的问题

当成员变量和函数参数同名时,可以用 this 指针来区分。

示例:

c++ 复制代码
class Example {
private:
    int value;

public:
    void setValue(int value) {
        this->value = value; // 使用 this 区分成员变量和参数
    }

2. 支持方法链调用

通过返回 *thisthis,可以支持链式调用(method chaining)。

示例:

c++ 复制代码
#include <iostream>
using namespace std;

class Example {
private:
    int value;

public:
    Example& setValue(int v) {
        value = v;
        return *this; // 返回当前对象的引用
    }

    Example& increment() {
        value++;
        return *this; // 返回当前对象的引用
    }

    void display() {
        cout << "Value: " << value << endl;
    }
};

int main() {
    Example obj;
    obj.setValue(10).increment().display(); // 链式调用
    return 0;
}

输出:

复制代码
Value: 11
相关推荐
Drone_xjw13 小时前
Qt国际化多语言配置详解-入门到精通
开发语言·qt·命令模式
爱吃提升13 小时前
Python 多线程 threading + 多进程 multiprocessing 完整实操教程
开发语言·python
不会C语言的男孩13 小时前
C++ Primer 第18章:用于大型程序的工具
开发语言·c++
星恒随风13 小时前
C++ 类和对象入门(三):拷贝构造、赋值运算符重载和深浅拷贝
开发语言·c++·笔记·学习
Cx330❀13 小时前
【MySQL基础】库与表的全面操纵指南
linux·服务器·网络·数据库·c++·mysql
RickyWasYoung13 小时前
【Matlab】科研绘图配色-极简版
开发语言·matlab
凡人叶枫13 小时前
Effective C++ 条款03:尽可能使用 const
linux·开发语言·c++·嵌入式开发
光影62713 小时前
Python接口自动化测试----Requests库基础入门
开发语言·python·测试工具·pycharm·自动化
程序媛_13 小时前
【Python】连接PostgreSQL获取手机验证码
开发语言·python·postgresql
ch.ju13 小时前
Java Programming Chapter 4——Inherited call
java·开发语言