1. this指针的用处:
一个对象的this指针并不是对象本身的一部分,不会影响sizeof(对象)的结果。this作用域是在类内部,当在类的非静态成员函数中访问类的非静态成员的时候,编译器会自动将对象本身的地址作为一个隐含参数传递给函数。也就是说,即使你没有写上this指针,编译器在编译的时候也是加上this的,它作为非静态成员函数的隐含形参,对各成员的访问均通过this进行。
2. this指针的使用:
1.在类的非静态成员函数中返回类对象本身的时候,直接使用 return *this;
#include <iostream>
using namespace std;
class Test;
void fun(Test *t);
class Test{
int a;
int b;
public:
Test(int x,int y):a(x),b(y){}
void print(){
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
Test mul()
{
this->a=this->a*2;
this->b=this->b*3;
return *this;
}
};
int main(int argc,char**argv)
{
Test test(1,2);
Test test1=test.mul();//默认赋值运算符重载
test1.print();
return 0;
}
2.当参数与成员变量名相同时,如this->n = n (不能写成n = n);
#include <iostream>
using namespace std;
class Test;
void fun(Test *t);
class Test{
int a;
int b;
public:
Test(int x,int y):a(x),b(y){}
void print(){
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
int mul(int a=1)
{
this->a=this->a*a;
return this->a;//20
//return a;//10
}
};
int main(int argc,char**argv)
{
Test test(2,3);
int result=test.mul(10);
cout<<"result="<<result<<endl;
return 0;
}
ps:尽量保证形参名不同于成员变量名
3.成员函数可以传递this指针给非成员函数;
#include <iostream>
using namespace std;
class Test;
void fun(Test *t);
class Test{
int a;
int b;
public:
Test(int x,int y):a(x),b(y){}
void print(){
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
void call()
{
fun(this);
}
};
void fun(Test *t)
{
t->print();
}
int main(int argc,char**argv)
{
Test test(1,2);
test.call();
return 0;
}
成员函数call传递实例化对象test所在地址给fun函数,fun函数使用this指针调用该对象的成员函数
3. this指针程序示例:
this指针存在于类的成员函数中,指向被调用函数所在的类实例的地址。
#include<iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b) { x=a; y=b;}
void MovePoint( int a, int b){ x+=a; y+=b;}
void print(){ cout<<"x="<<x<<"y="<<y<<endl;} <="" font="">
};
void main()
{
Point point1( 10,10);
point1.MovePoint(2,2);
point1.print();
}
当对象point1调用MovePoint(2,2)函数时,即将point1对象的地址传递给了this指针。
MovePoint函数的原型应该是
void MovePoint( Point *this, int a, int b);
第一个参数是指向该类对象的一个指针,它是隐含的
void MovePoint(int a, int b) { this->x +=a; this-> y+= b;}
即可以知道,point1调用该函数后,也就是point1的数据成员被调用并更新了值。即该函数过程可写成
point1.x+= a; point1. y + = b;
调用过程应为:
point1.MovePoint(&point1,2,2);
5. 类的this指针有以下特点:
(1)this只能在成员函数中使用。
全局函数、静态函数都不能使用this.
实际上,成员函数默认第一个参数为T * const this。
如:
class A
{
public:
int func(int p){}
};
其中,func的原型在编译器看来应该是:
int func(A * const this,int p);
(2)由此可见,this在成员函数的开始前构造,在成员函数的结束后清除。
这个生命周期同任何一个函数的参数是一样的,没有任何区别。
当调用一个类的成员函数时,编译器将类的指针作为函数的this参数传递进去。如:
A a;
a.func(10);
此处,编译器将会编译成:
A::func(&a,10);