c++++ 中 this 指针指向调用函数的类实例,便于访问成员变量和方法。具体用法包括:在非静态成员函数中,this 指向调用实例。在静态成员函数中,this 为 nullptr。通过 this->成员变量访问成员变量。通过 this->成员函数() 调用成员函数。

C++ 函数中 this 指针的含义和用法
this 指针是一个指向调用函数的类的实例的指针。它允许函数访问类的成员变量和方法。
含义
立即学习“C++免费学习笔记(深入)”;
用法
this->成员变量
this->成员函数()
实战案例
考虑以下 Person 类:
class Person {
public:
string name;
int age;
void introduce() {
cout << "我的名字叫 " << this->name << ", 年龄是 " << this->age << "." << endl;
}
};在 main 函数中:
int main() {
Person p1;
p1.name = "小明";
p1.age = 20;
p1.introduce(); // 调用 Person 的 introduce 方法
return 0;
}在 introduce() 方法中,this 指针指向 p1 实例,因此可以访问其 name 和 age 成员变量。输出结果为:
我的名字叫小明, 年龄是20.
以上就是C++ 函数中this指针的含义和用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号