四个问题
1. this指针占不占用类、对象的大小?
'this指针不占用类的大小,它是右编译器帮我们传递的'
2. this指针地址里面放的是什么?
'this指针是指向自身的地址,也就是指向对象的指针','是对象的首地址'
3. '成员变量分为静态和非静态,类的静态成员函数没办法操作this?为什么?'
' 静态函数优先于对象存在,是所有对象公有的'
4. 为什么要设计this?
'c++对象模型,区分作用域,返回自引用,在类的内部销毁自身'
引入this
- 类的
成员函数
可以访问类的数据(限定符只是限定于类外的一些操作,类内的一切对于成员函数来说都是透明的),那么成员函数如何知道哪个对象的数据成员要被操作呢,原因在于每个对象都拥有一个指针:this指针,通过this指针来访问自己的地址。
注意点
- this只能在成员函数中使用(this只能在类内成员函数中使用,不能在类外使用)
- 成员函数默认第一个参数为
T* const register this。
(友元函数,全局函数不是成员函数)
- this指针不能再静态成员函数中使用
- 静态函数类似于静态变量,不是针对某一个类的,是所有对象公有的,因此静态函数优先与对象产生,而
this
指针指向的就是对象的首地址,因此this指针不能在静态成员函数中使用
- this指针只有在成员函数中才有定义。
- 创建一个对象后,不能通过对象使用this指针。也无法知道一个对象的this指针的位置(只有在成员函数里才有this指针的位置)。当然,在成员函数里,你是可以知道this指针的位置的(可以
&this
获得),也可以直接使用的。
- this指针的创建
- this指针在成员函数的开始执行前构造的,在成员的执行结束后清除。
this指针用处
- 每个类都有一个
this
指针,我们的成员函数可以通过这个this
指针来操作对象的成员属性
#include <iostream>
using namespace std;
class Student{
public:
int getAge(){
return age;
}
Student setAge(int age){
this->age = age;
cout << "age =" << age << endl;
return *this;
}
private:
int age;
};
int main()
{
Student s;
s.setAge(18);
cout << s.getAge() << endl;
return 0;
}
验证上述四个问题
'问题1:'
#include <iostream>
using namespace std;
class Student{
public:
int getAge(){
return age;
}
Student setAge(int age){
this->age = age;
cout << "age =" << age << endl;
return *this;
}
private:
int age;
};
int main()
{
cout <<"sizeof(Student) = "<< sizeof(Student) << endl;
return 0;
}
运行结果:sizeof(Student) = 4
'问题2:'
#include <iostream>
using namespace std;
class Student{
public:
void test()
{
cout << "this 指针里面存放的地址是什么" << this << endl;
}
private:
int age;
};
int main()
{
Student s;
s.test();
cout << "s 实例对象的地址:"<< &s << endl;
return 0;
}
运行结果:this 指针里面存放的地址是什么0x61fe1c
s 实例对象的地址:0x61fe1c

'问题3:'
#include <iostream>
using namespace std;
class Student{
public:
static void lazy()
{
cout << "i want sleep" << endl;
}
private:
int age;
};
int main()
{
'调用第一次是没有创建对象,但是this指向的是实例化对象的首地址'
'原因:静态成员函数优先对象存在的,因此静态成员函数无this指针'
Student::lazy();
Student s;
s.lazy();
return 0;
}
运行结果:
i want sleep
i want sleep