2014-10-30 26 views
0

Win7的 Cygwin的如何使用向量作爲基類

這在我第一次使用的模板&容器。我不明白這些錯誤。對於我的(幼稚的)看待事物的方式,我定義了一個分配器(_Alloc)和一個typdef(allocator_Type)。這些消息似乎是在說我沒有正確完成我的功課。我不知道該怎麼做。

的代碼是:

template<typename T, typename _Alloc = std::allocator<T>> 
class Array : public vector<T, _Alloc> { 
    public: 
     typedef T   value_type; 
     typedef _Alloc allocator_Type; 
    private: 
    int compar (const void* p1, const void* p2) { T v1 = (T)*p1; 
               T v2 = (T)*p2; 
               return (v1 < v2)? -1: (v1 > v2)? 1: 0; } 
    public: 
    explicit Array (const allocator_Type& alloc = allocator_type()) : vector<T, _Alloc>(alloc) { }; 
    explicit Array (size_t n)          : vector<T, _Alloc>(n)  { }; 
      Array (size_t n, const T& val, 
        const allocator_type& alloc = allocator_type()): vector<T, _Alloc>(n, val, alloc) { }; 
}; 

錯誤形式交往是:

main.cpp:31:27: error: 'allocator_type' does not name a type 
        const allocator_type& alloc = allocator_type()): vector<T, _Alloc>(n, val, alloc) { }; 
         ^
main.cpp:31:27: note: (perhaps 'typename std::vector<_Tp, _Alloc>::allocator_type' was intended) 
main.cpp:31:66: warning: ISO C++ forbids declaration of 'alloc' with no type [-fpermissive] 
        const allocator_type& alloc = allocator_type()): vector<T, _Alloc>(n, val, alloc) { }; 
                   ^
main.cpp:28:65: warning: there are no arguments to 'allocator_type' that depend on a template parameter, so a declaration of 'allocator_type' must be available [-fpermissive] 
    explicit Array (const allocator_Type& alloc = allocator_type()) : vector<T, _Alloc>(alloc) { }; 
                   ^
main.cpp:31:66: warning: there are no arguments to 'allocator_type' that depend on a template parameter, so a declaration of 'allocator_type' must be available [-fpermissive] 
        const allocator_type& alloc = allocator_type()): vector<T, _Alloc>(n, val, alloc) { }; 
                   ^
+10

要注意,'std :: vector'的析構函數沒有聲明爲虛擬的,因此不應該被用作基類。 – Borgleader 2014-10-30 14:28:05

+7

「你如何使用向量作爲基類」 - 你**不**。 'std :: vector'被設計爲被封裝,而不是被繼承。 – utnapistim 2014-10-30 14:30:42

+2

'typedef _Alloc allocator_Type'是實際的名稱。你用小寫字母寫了'allocator_type'。 – 0x499602D2 2014-10-30 14:31:43

回答

0

首先 - 你有一個錯字:大寫T IN allocator_Type和小寫在常量allocator_Type &的alloc = allocator_type()。第二個 - std :: vector析構函數不是虛擬的,因此除非您從不通過基類進行投射和刪除,否則您不應該從它派生出來。

1

這已在評論中聲明,但尚未發佈爲答案:您不需要

標準庫容器不應該用作(公共)基類。它們是非多態的,所以你不能將從一個派生出來的對象安全地傳遞給任何期望指向容器的指針或引用的函數。

理論上,您可以使用標準容器作爲私有基類。這與私有成員變量具有相同的語義,但是如果您只使用了私有成員變量,它將使您的代碼更容易遵循其他的代碼。