This
C++ 中的每个对象都可以通过称为 this 指针访问自己的地址。
在成员函数内部,这可以用来引用调用对象。
我们来创建一个示例类:
class MyClass {
public:
MyClass(int a) : var(a)
{ }
private:
int var;
};
友元函数没有这个指针,因为友元不是一个类的成员。
注:友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数。类授予它的友元特别的访问权。通常同一个开发者会出于技术和非技术的原因,控制类的友元和成员函数(否则当你想更新你的类时,还要征得其它部分的拥有者的同意)。
printInfo() 方法为打印类的成员变量提供了三种选择。
class MyClass {
public:
MyClass(int a) : var(a)
{ }
void printInfo() {
cout << var<<endl;
cout << this->var<<endl;
cout << (*this).var<<endl;
}
private:
int var;
};
所有三种选择将产生相同的结果。
this 是一个指向对象的指针,所以使用箭头选择操作符来选择成员变量。

为了看到结果,我们可以创建我们的类的一个对象,并调用成员函数。
#include <iostream>
using namespace std;
class MyBlog{
public:
MyBlog(string a): name(a)
{}
void printInfo(){
cout <<name <<endl;
cout <<this->name <<endl;
cout <<(*this).name <<endl;
cout <<this->getname() <<endl;
cout <<(*this).name <<endl;
}
string getname(){
return name;
};
private:
string name;
};
int main()
{
MyBlog rhz("RHZ的博客");
rhz.getname();
rhz.printInfo();
}
/* Outputs
RHZ的博客
RHZ的博客
RHZ的博客
RHZ的博客
RHZ的博客
*/
所有这三种访问成员变量的方式都起作用。
请注意,只有成员函数有一个 this 指针。
你可能想知道为什么要使用 this 关键字,因为我们可以用直接选择变量名的方式来进行访问。
实际上,这个关键字在操作符重载中起着重要的作用,这将在下一篇文章(操作符重载|C++)中介绍。

文章评论
Everything is very open with a really clear clarification of the challenges. It was really informative. Your website is extremely helpful. Thank you for sharing!