This 指针:this 是C++中的一个关键字,也是一个常量指针,指向当前对象(具体说是当前对象的首地址) 。通过 this,可以访问当前对象的成员变量和成员函数 。
Student Stu ; //通过Student类创建对象 Stu
Student *pStu =&pStu ;
假设this 指向对象 Stu , 则this 的值和 &pStu 相同 。
eg 1: 通过 this 指针来访问 Student 类的成员变量和成员函数:
class Student{
private:
char *name;
int age;
float score;
public:
void setName(char *name);
void setAge(int age);
void setScore(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;
}
本例通过this 访问对象 Stu 的成员变量,而没有this的是函数内部的局部变量,所以在本例中函数参数和成员变量可以重名。即:this->score = score;
eg2 :
#include <iostream>
#include <stdlib.h>
using namespace std;
class Student{
private:
char *name;
int age;
float score;
public:
void setName(char *name);
void setAge(int age);
void setScore(float score);
void printStudent();
};
void Student::setName(char *name){
this->name = name;
}
void Student::setAge(int age){
this->age = age;
}
void Student::setScore(float score){
this->score = score;
}
voidStudent::printStudent(){
cout<<this->name<<"的年龄是 "<<this->age<<",成绩是 "<<this->score<<endl;
}
int main(){
Student stu1;
stu1.setName("张三");
stu1.setAge(15);
stu1.setScore(90.5f);
stu1.printStudent();
Student stu2;
stu2.setName("李四");
stu2.setAge(16);
stu2.setScore(80);
stu2.printStudent();
system("pause");
return 0;
}
运行结果;
对象和普通变量类似;每个对象都占用若干字节的内存,用来保存成员变量的值,不同对象占用的内存互不重叠,所以操作对象A不会影响对象B。
上例中,创建对象 stu1 时,this 指针就指向了 stu1 所在内存的首字节,它的值和 &stu1 是相同的;创建对象 stu2 时,this 等于 &stu2;创建对象 stu3 时也一样
在main 函数中创建两个新对象Stu1 和 Stu2
Student stu1;
Student *pStu1 = &stu1;
stu1.printThis();
cout<<pStu1<<endl;
Student stu2;
Student *pStu2 = &stu2;
stu2.printThis();
cout<<pStu2<<endl;
运行结果:
显然this 指针指向了当前对象的首地址,访问不同的对象,this的指向不同。
this的作用:
一种情况就是,在类的非静态成员函数中返回类对象本身的时候,直接使用 return *this;。
一个对象的this指针并不是对象本身的一部分,不会影响sizeof(对象)的结果。this作用域是在类内部,当在类的非静态成员函数中访问类的非静态成员的时候,编译器会自动将对象本身的地址作为一个隐含参数传递给函数。
this 的实质:
实际上,this 指针是作为函数的参数隐式传递的,它并不出现在参数列表中,调用成员函数时,系统自动获取当前对象的地址,赋值给 this,完成参数的传递,无需用户干预。
this 作为隐式参数,本质上是成员函数的局部变量,不占用对象的内存,只有在发生成员函数调用时才会给 this 赋值,函数调用结束后,this 被销毁。
因为 this 是参数,表示对象首地址,所以只能在函数内部使用,并且对象被实例化以后才有意义。
this是成员函数和成员变量关联的桥梁。
注:
(1)this 是常量指针,它的值是不能被修改的,一切企图修改该指针的操作,如赋值、递增、递减等都是不允许的。
(2)this 只能在成员函数内部使用,其他地方没有意义,也是非法的,。
(3)只有当对象被创建后 this 才有意义
(4)this在成员函数的开始执行前构造,在成员的执行结束后清除。
(5)this指针会因编译器不同而有不同的放置位置。可能是栈,也可能是寄存器,甚至全局变量。
895

被折叠的 条评论
为什么被折叠?



