2012-12-19 173 views
6

只是偶然發現了一些我無法解釋的東西。下面的代碼無法編譯有時需要使用這個嗎?

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(); 
} 

而當我改變_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 
+3

上[兩階段名稱查找](閱讀起來http://blog.llvm.org/2009/12/dreaded-兩相名稱lookup.html)。 (也是這個FAQ:[爲什麼當我的模板派生類使用從它的模板基類繼承的成員時,我得到錯誤?](http://www.parashift.com/c++-faq/nondependent-name -lookup-members.html)) – ildjarn

回答

7

Why is that? Are there any cases you must to use this?

是的,有一些情況下,你需要使用this。在你的例子中,當編譯器看到_attr時,它試圖在類內部尋找_attr並找不到它。通過添加this->延遲查找直到實例化時間,它允許編譯器在sub的內部找到它。

另一種非常常見的理由使用,這是解決問題的不確定性:

void foo (int i) 
{ 
    this->i = i; 
} 
+0

謝謝。是否知道歧義用法,但那是新的... – Ace7k3