c++ - 如何使用 vector 作为基类

标签 c++ templates inheritance c++11

Win7 赛格文

这是我第一次使用模板和容器。我不明白这些错误。根据我(天真的)看待事物的方式,我定义了一个分配器 (_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) { };
                                                                  ^

最佳答案

这已在评论中说明但尚未作为答案发布:你没有

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

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

关于c++ - 如何使用 vector 作为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26655633/

相关文章:

c++ - 防止模板中的内存泄漏

java - 如何使用 JDK8 可选为可空字段创建自定义 IntelliJ getter 模板

c++ - 从派生类引用基类的更好习惯用法?

c++ - 使用 getline 读取 .csv 文件时遇到问题

C++读取带空格的字符串

c++ - 我怎样才能找到当前内存地址的值?

c++ - 使用 OMPL Planner 区分超时和阈值匹配

c++ - integer_sequence 如何展开以生成序列?

javascript - 如何通过继承向现有功能添加功能

c++ - 为什么我不能访问作为参数传递给函数的基类的 protected 成员变量?