2010-09-01 76 views
5

我需要對問題進行一些說明,爲什麼我們需要範圍解析運算符或this指針從模板基類訪問公共繼承成員。 據我所知,它是爲了增加清晰度,但this如何增加任何進一步的澄清,而不僅僅是它是該類的成員。訪問公有繼承模板數據成員

爲了讓我的問題更清晰,我添加了一些代碼。

#include <iostream> 
using namespace std; 

template <class T, class A> 
class mypair { 
     public: 
     T a, b; 
    public: 
    mypair (T first, T second) 
     {a=first; b=second;} 

     virtual void printA() 
     { 
     cout<<"A"<<a<<endl; 
     cout<<"B"<<b<<endl; 
     } 
}; 







template <class T, class A> 
class next: mypair<T,A> 
{ 
public: 

     next (T first, T second) : mypair<T,A>(first, second) 
     { 
     } 

     void printA() 
     { 
     cout<<"A:"<<mypair<T,A>::a<<endl; // this->a; also works 
     cout<<"B:"<<mypair<T,A>::b<<endl; // this-b; also works 
     } 

}; 


int main() { 
    next<double,float> newobject(100.25, 75.77); 
    newobject.printA(); 
    return 0; 
} 

輸出:

A:100.25 
B:75.77 

如果刪除的範圍(或這個操作符),則出範圍誤差均。 但爲什麼我們需要一個公開繼承的成員的範圍。

對此的一些想法會很棒。

回答

4

參考Name lookup - Using the GNU Compiler Collection (GCC)

通過添加前綴明確mypair<T, A>,或this->,你讓printA模板參數依賴。然後這些定義將在模板實例化階段解析。

+0

有趣的閱讀 那麼這是一個只有模板的特例嗎? – Sii 2010-09-01 08:23:45

+0

僅限模板類中的函數。 – 2010-09-02 08:49:49