2011-11-17 83 views
1

如果我有這樣的層次:公共繼承的模板友元類

#include <iostream> 

using namespace std; 

template<class T> 
class typeB; 

template<class T> 
class typeA 
{ 
    // Private data 
     T* x_; 
     int size_; 
    public: 
     // Constructors 
     typeA() 
      : x_(0), size_(0) 
     { 
     }; 
     typeA(int size) 
      : x_(0), size_(size) 
     { 
     } 

     // Friend classes. 
     friend class typeB<T>; 
}; 

template<class T> 
class typeB 
: public typeA<T> 
{ 
    public: 
     // Constructors 
     typeB() 
     { 
     }; 
     typeB (int size) 
      : typeA<T>(size) 
     { 
      //this->x_ = new T[size]; 
      x_ = new T[size]; 
     } 
}; 

int main() 
{ 
    typeB<int> b(4); 

    return 0; 
} 

爲什麼我需要指定「這個 - > X_ =新的T [尺寸]」中的TypeB(INT大小)構造函數,而不是「x_ = new T [size]」來獲得這段代碼來編譯?

什麼編譯器告訴我的是,它無法解決X_類型:

main.cpp: In constructor ‘typeB<T>::typeB(int)’: 
main.cpp:42: error: ‘x_’ was not declared in this scope 

如果是的TypeB的的typeA的朋友,它應該有公衆獲取的typeA屬性。如果我試試這個非模板類,它的工作原理:

#include <iostream> 

using namespace std; 

class typeB; 

class typeA 
{ 
    // Private data 
     int* x_; 
     int size_; 
    public: 
     // Constructors 
     typeA() 
      : x_(0), size_(0) 
     { 
     }; 
     typeA(int size) 
      : x_(0), size_(size) 
     { 
     } 

     // Friend classes. 
     friend class typeB; 
}; 

class typeB 
: public typeA 
{ 
    public: 
     // Constructors 
     typeB() 
     { 
     }; 
     typeB (int size) 
      : typeA(size) 
     { 
      x_ = new int[size]; 
     } 
}; 

int main() 
{ 
    typeB b(4); 

    return 0; 
} 

的typeA和TYPEB是一種列表容器:你認爲什麼是對這樣一種關係(public繼承+朋友的動機,VS如果需要直接訪問,將x_和size_作爲受保護屬性)?

回答

3

首先,成員x_是基類的私有成員。在這裏,友誼不會幫助你,因爲你試圖訪問繼承。

即使您對其進行保護或公開,模板基類的成員也不會在派生類中自動顯示。

的解決方案是:

  1. 使用this->明確的,

  2. 或將名稱爲派生類範圍爲:

    template<class T> 
    class typeB : public typeA<T> 
    { 
         using typeA<T>::x_; //brings the name x_ into the class scope! 
         //... 
    

    ,那麼你可以寫

    x_ = new int[size]; 
    
+0

即使模板類是朋友,這是否有效? – tmaric

+0

我的意思是說,如果私有屬性在typeA中被聲明爲受保護,那麼它可能會更容易,在這種情況下,如果繼承是公共的,那麼它們可以通過typeB方法直接尋址。 – tmaric

+0

@ tomislav-maric:是的。 – Nawaz