只是偶然发现了一些我无法解释的事情.以下代码无法编译
template<int a>
class sub{
protected:
int _attr;
};
template<int b>
class super : public sub<b>{
public:
void foo(){
_attr = 3;
}
};
int main(){
super<4> obj;
obj.foo();
}
Run Code Online (Sandbox Code Playgroud)
而当我改变_attr = 3;
到this->attr = 3;
那里似乎没有问题.
这是为什么?有什么情况你必须使用它吗?
我曾经g++ test.cpp -Wall -pedantic
编译,我得到以下错误
test.cpp: in member function 'void super<b>::foo()':
test.cpp:11:3: error: '_attr' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
Why is that? Are there any cases you must to use this?
是的,在某些情况下您需要使用this
.在您的示例中,当编译器看到时_attr
,它会尝试_attr
在类中查找并找不到它.通过添加this->
你延迟的查找,直到实例化时,它允许编译器发现它的内部sub
.
使用此功能的另一个常见原因是解决模糊问题:
void foo (int i)
{
this->i = i;
}
Run Code Online (Sandbox Code Playgroud)