菜鸟学编程,不懂C++ this指针?还不赶快来学一学

本文章向大家介绍C++ this指针 , 主要包括C++ this指针使用实例、应用技巧、基本知识点总结和需要注意事项 , 具有一定的参考价值 , 需要的朋友可以参考一下 。
菜鸟学编程,不懂C++ this指针?还不赶快来学一学文章插图
this是C++中的一个关键字 , 也是一个const指针 , 它指向当前对象 , 通过它可以访问当前对象的所有成员 。 所谓当前对象 , 就是正在使用的对象 。 例如对于stu.show() , stu就是当前对象 , this就指向stu 。
#include
using namespace std;
class Student
{
public:
void setname(char *name);
void setage(int age);
void setscore(float score);
void show();
private:
char *name;
int age;
float score;
};
void Student::setname(char *name)
{
this -> name = name;
}
void Student::setage(int age)
{
this -> age = age;
}
void Student::setscore(float score)
{
this -> score = score;
}
void Student::show()
{
cout << this -> name << "的年龄是" << this -> age << " , 成绩是" << this -> score << endl;
}
int main()
{
Student *pstu = new Student;
pstu -> setname("李华");
pstu -> setage(16);
pstu -> setscore(96.5);
pstu -> show();
return 0;
}
//运行结果:李华的年龄时16 , 成绩是96.5
this只能用在类的内部 , 通过this可以访问类的所有成员 , 包括private、protected、public属性的 。 只有在对象被创建后才会给this赋值 。
菜鸟学编程,不懂C++ this指针?还不赶快来学一学文章插图
注意:this是一个指针 , 要用->来访问成员变量或成员函数 。
//给Student类添加一个成员函数printThis() , 专门用来输出this的值
void Student::printThis()
{
cout << this << endl;
}
//然后再main函数中创建对象并调用printThis()
Student *pstu1 = new Student;
pstu1 -> printThis();
cout << pstu1 << endl;
Student *pstu2 = new Student;
【菜鸟学编程,不懂C++ this指针?还不赶快来学一学】pstu2 -> printThis();
cout << pstu2 << endl;
//运行结果:
0x7c1510
0x7c1510
0x7c1530
0x7c1530
this确实指向了当前对象 , 而且对于不同的对象 , this的值也不一样 。
注意:
this是const指针 , 它的值是不能被修改的 , 一切企图修改该指针的操作 , 如赋值、递增、递减等都是不允许的 。
this只能在成员函数内部使用 , 用在其他地方没有意义 , 也是非法的 。
只有当对象被创建后this才有意义;因此不能在static成员函数中使用 。
菜鸟学编程,不懂C++ this指针?还不赶快来学一学文章插图
this到底是什么?
this实际上是成员函数的一个形参 , 在调用成员函数时将对象的地址作为实参传递给this 。 不过this这个形参是隐式的 , 它并不出现在代码中 , 而是在编译阶段由编译器默默的将它添加到参数列表中 。
this作为隐式形参 , 本质上是成员函数的局部变量 , 所以只能用在成员函数的内部 , 并且只有在通过对象调用成员函数时才给this赋值 。
成员函数最终被编译成与对象无关的普通函数 , 除了成员变量 , 会丢失所有信息 , 所以编译时要在成员函数中添加一个额外的参数 , 把当前对象的首地址传入 , 依次来关联成员函数和成员变量 。 这个额外的参数 , 实际上就是this , 它是成员函数和成员变量关联的桥梁 。