#include <iostream>
#include <string>

int main() {
    // 定义一个Lambda函数,捕获this指针并接受字符串引用参数
    auto lambda = [](std::string &str) {
        // 在这里可以对字符串进行操作
        // 例如:将字符串转换为大写
        for (char &c : str) {
            c = toupper(c);
        }
    };
    
    std::string text = "hello world";
    std::cout << "原始字符串: " << text << std::endl;
    
    // 调用Lambda函数
    lambda(text);
    
    std::cout << "处理后字符串: " << text << std::endl;
    
    return 0;
}
#include <iostream>
#include <string>

int main() {
    // 定义一个Lambda函数,捕获this指针并接受字符串引用参数
    auto lambda = [this](std::string &str) {
        // 在这里可以对字符串进行操作
        // 例如:将字符串转换为大写
        for (char &c : str) {
            c = toupper(c);
        }
    };
    
    std::string text = "hello world";
    std::cout << "原始字符串: " << text << std::endl;
    
    // 调用Lambda函数
    lambda(text);
    
    std::cout << "处理后字符串: " << text << std::endl;
    
    return 0;
}

this指针是C++面向对象编程中的一个重要概念。它是一个隐含的指针,指向当前正在调用成员函数的对象。

在C++中,当一个成员函数被调用时,编译器会自动将当前对象的地址作为隐含参数传递给该函数。this指针就是用来接收这个地址的指针变量。它允许成员函数访问当前对象的成员变量和成员函数。

例如,当调用对象的成员函数时,this指针指向该对象本身。在成员函数内部,可以通过this指针来访问对象的成员变量,或者调用其他成员函数。

this指针在以下场景中特别有用:

当成员变量与参数同名时,用于区分成员变量和参数
在成员函数中返回对象本身(链式调用)
在构造函数中避免无限递归调用
在重载运算符时使用

this指针是每个非静态成员函数都隐含拥有的,它在类的成员函数内部自动可用,无需显式声明或传递。

#include <iostream>
#include <string>

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

public:
    Student(const std::string& n, int a) : name(n), age(a) {}
    
    // 使用this指针区分成员变量和参数
    void setName(const std::string& name) {
        this->name = name;  // this->name是成员变量,name是参数
    }
    
    void setAge(int age) {
        this->age = age;    // this->age是成员变量,age是参数
    }
    
    // 返回当前对象的引用,实现链式调用
    Student& setInfo(const std::string& n, int a) {
        this->name = n;
        this->age = a;
        return *this;  // 返回当前对象的引用
    }
    
    void display() const {
        std::cout << "姓名: " << name << ", 年龄: " << age << std::endl;
    }
};

int main() {
    Student s("张三", 20);
    s.display();
    
    s.setName("李四");
    s.setAge(22);
    s.display();
    
    // 使用链式调用
    s.setInfo("王五", 25);
    s.display();
    
    return 0;
}

更多推荐