這個
在類的成員函式中,關鍵字 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 是一個右值,因此無法分配。