如何使用向量作为基类

How do you use vector as a base class

本文关键字:基类 向量 何使用      更新时间:2023-10-16

Win7Cygwin

这是我第一次使用模板&集装箱。我不明白这些错误。对于我(天真的)看待事物的方式,我定义了一个分配器(_Alloc)和一个typdef(分配器类型)。这些信息似乎是在说我没有做好家庭作业。我不知道该怎么办。

代码为:

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) { };
                                                                  ^

这已经在评论中说明了,但还没有作为答案发布:你不

标准库容器不应该用作(公共)基类。它们是非多态的,因此不能将从一个派生的对象安全地传递给任何需要指向容器的指针或引用的函数。

理论上,您可以使用标准容器作为私有基类。这与私有成员变量具有相同的语义,但如果您只使用私有成员变量,它将使您的代码更容易为其他人所遵循。

首先,您有一个拼写错误:allocator_Type中的大写T和const allocator_Type&alloc=分配器类型()。第二个std::vector析构函数不是虚拟的,因此您不应该从它派生,除非您从未通过基类进行强制转换和删除。