自引用指针this
this指针:
成员函数隐藏定义的常量指针
- 类型:类的类型
- 指向:当前对象
- 通过它可以访问当前对象的所有成员
- 在通常情况下,this指针在系统中是隐含地存在的。也可以将其显式地表示出来。
- const指针,不能在程序中修改或赋值
- 作用域在对象内部,可通过this访问private,public,protected属性成员
- 对象被创建后才给this赋值,由编译器自动完成
调用:
调用成员函数时,它被初始化为被调函数所在类的对象的地址。也就是自动地将对象的指针传给它。
不同的对象调用同一个成员函数时,编译器将根据成员函数的this指针所指向的对象来确定应该引用哪一个对象的数据成员。
【Example 1】显式表示this指针
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A(int x1) { x = x1; }
void disp()
{
cout << "this=" << this << "\tx=" << this->x << endl;
}
};
int main()
{
A a(1), b(2), c(3);
a.disp();
b.disp();
c.disp();
return 0;
}
/*
output:
this=0x61feec x=1
this=0x61fee8 x=2
this=0x61fee4 x=3
*/
【Example 2】this和*this的用法
#include <stdlib.h>
#include <iostream>
using namespace std;
class Sample
{
private:
int x, y;
public:
Sample(int i=0,int j=0)
{
x = i;
y = j;
cout << "constructing..." << endl;
}
void copy(Sample &s){
if(this==&s) // 若拷贝其本身,则直接返回
return;
*this = s; // 深拷贝?
// *this表示当前对象本身
}
void print(){
cout << x << "," << y << endl;
}
void set_x(int x) { this->x = x; }
~Sample()
{
cout << "destructing..." << endl;
}
};
int main()
{
Sample p1(1, 1), p2(5, 6);
p1.print();
p2.print();
p1.copy(p2);
p1.print();
p2.set_x(2);
p2.print();
p1.print();
return 0;
}
/*
output:
constructing...
constructing...
1,1
5,6
5,6
2,6
5,6
destructing...
destructing...
*/