关键词this是一个指针,这个指针是指向自己的一个指针,也即this是向某些需要使用到本身地址的地方传递对象本身的地址。this只能在类中的方法使用,不能出现在main或其他函数中。例如下面的程序:
#include <iostream>
using namespace std;
class A{
public:
A(){}
~A(){}
void adress(){
cout << this <<endl;
}
};
int main(){
A a;
cout << "直接输出对象a的地址:\n";
cout << &a <<endl;
cout << "通过this指针输出对象a的地址:\n";
a.adress();
}
输出结果:
两种情况输出的同一对象的地址完全相同,因此this其实就是本对象的地址。同样地,也可通过this操作对象中的方法或属性,但一般情况下,这种this可以省略不写。例如下面的程序:
#include <iostream>
using namespace std;
class A{
public:
A(){}
void adress(){
cout << this <<endl;
}
void text(){
cout << "I would like to output the address of myself with method adress():\n";
this->adress(); //通过this调用adress和在本行直接写adress()结果相同
}
~A(){}
};
int main(){
A a;
a.text();
}
输出结果:
但是当需要使用与类中的属性或方法同名的变量或函数时,则此时的this不能省略,如下面的程序:
#include <iostream>
using namespace std;
class Complex{
double re;
double im;
public:
Complex(const double re, const double im){
this->re = re; //此时传递的形参和该类中的属性名相同,此处this不能省略
this->im = im;
}
void text(){
cout << "this complex number is:\n";
cout << this->re << " + " << this->im << "j\n"; //此处的两个this可以省略,此处并未出现同名情况
}
~Complex(){}
};
int main(){
Complex z = {4.0, 5.0};
z.text();
}
输出结果:
如果构造函数中的this省略了,那将会产生严重的逻辑错误(去掉const后),输出结果:
显然不是想要的结果。
如有错误,欢迎大家批评与指正!