#include <iostream>
using namespace std;
/*
this 指针是对象创建是产生的,对象没创建没有this指针
类型就是对应对象的类指针
注意this指针不是成员,this指针是类每个成员函数的隐含第一个参数,所以只能在成员函数内部使用this指针,无法在成员函数外部使用
*/
class CStu
{
public:
int a;
//this->a;//这里会报错,因为this指针只能在成员函数里使用
CStu(int a)//这里参数a(局部变量) 在构造函数内 因为变量作用域的原因,会覆盖掉类成员变量a
{
show();
//a = a; //这里两个a全是构造函数参数 a,成员变量a被覆盖掉了
this->a = a; // 要想使用成员变量a,就要用到this指针,本例中this指针的类型是 CStu*,指向当前对象
show();
this->show();
}
void show()
{
std::cout << a << std::endl;
}
//使用this指针常见地方
CStu * GetAddress() //得到对象的地址
{
return this;
}
CStu GetObject()
{
return *this;
}
};
int main()
{
CStu st(2);
st.show();
CStu *p = st.GetAddress();
cout << p << endl;
p->show();
CStu st2(13);
st2.show();
p = st2.GetAddress();
cout << p << endl;
cout << sizeof(p) << endl;
p->show();//这里通过对象地址调用类对象函数
//st.this;//这里报错,因为this指针不是类成员
return 0;
}