什么时候应该明确使用`this`指针? [英] When should I make explicit use of the `this` pointer?
问题描述
我应该何时在
a类的方法中明确写入 this-> member
?
推荐答案
通常,你不必, this->
是隐含的。
Usually, you do not have to, this->
is implied.
有时,有一个名称歧义,它可以用来消除类成员和局部变量的歧义。但是,这里有一个完全不同的情况,其中明确需要 this->
。
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this->
is explicitly required.
请考虑以下代码:
template<class T>
struct A {
int i;
};
template<class T>
struct B : A<T> {
int foo() {
return this->i;
}
};
int main() {
B<int> b;
b.foo();
}
如果省略 this->
,编译器不知道如何处理 i
,因为它可能存在或不存在于 A
。为了说明 i
确实是 A< T>
的成员,对于任何 T
,需要 this->
前缀。
If you omit this->
, the compiler does not know how to treat i
, since it may or may not exist in all instantiations of A
. In order to tell it that i
is indeed a member of A<T>
, for any T
, the this->
prefix is required.
注意:可以通过使用以下内容仍然省略 this->
前缀:
Note: it is possible to still omit this->
prefix by using:
template<class T>
struct B : A<T> {
using A<T>::i; // explicitly refer to a variable in the base class
int foo() {
return i; // i is now known to exist
}
};
这篇关于什么时候应该明确使用`this`指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!