这个
在类的成员函数中,关键字 this 是指向调用该函数的类的实例的指针。this 不能用于静态成员函数。
struct S {
int x;
S& operator=(const S& other) {
x = other.x;
// return a reference to the object being assigned to
return *this;
}
};
this 的类型取决于成员函数的 cv 资格:如果 X::f 是 const,那么 f 中的 this 的类型是 const X*,因此 this 不能用于修改 const 成员函数内的非静态数据成员。同样,this 从它出现的函数继承了 volatile 资格。
Version >= C++ 11
this 也可以用于非静态数据成员的大括号或等于初始化程序。
struct S;
struct T {
T(const S* s);
// ...
};
struct S {
// ...
T t{this};
};
this 是一个右值,因此无法分配。