2012-12-19 9 views
6

私は説明できない何かにつまずいた。次のコードは、私は何の問題もないように思わ_attr = 3;this->attr = 3;に変化したときには時にはこれを使用する必要がありますか?

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

をコンパイルしません。

なぜですか?これを使用する必要がある場合はありますか?

私はコンパイルする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-:

これを使用するには、別の非常に一般的な理由は、曖昧さの問題を解決することですtwo-phase-name-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

関連する問題