如何使用向量作为基类
How do you use vector as a base class
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析构函数不是虚拟的,因此您不应该从它派生,除非您从未通过基类进行强制转换和删除。
相关文章:
- 如何通过派生类函数更改基类中的向量
- 如何在基类指针向量的元素上应用重载的多态函数
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 如何访问基类向量中的子类变量?(对于实体组件系统)
- CRTP 与基类向量
- 基类到派生类的强制转换向量
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- 有没有办法复制派生类指针的向量而不将其强制转换为基类?
- 将抽象派生类对象存储在基类向量中
- 如何从基类向量达到派生的类变量
- 将子类添加到基类向量C++不起作用
- 如何将子类向量传递给需要基类向量的函数
- 如何查找多态基类向量中包含的对象的类型?
- 最佳做法:将派生类的向量传递给基类向量上的方法
- 将子类添加到基类向量
- 尝试从从 DLL 加载的驱动类实例访问基类向量成员时,程序崩溃
- 如何在C ++的基类向量中找到哪个派生类
- 具有基类向量的类的下标运算符重载,该向量必须返回派生类
- reinterpret_cast派生类向量到基类向量
- 从子类的STL向量到基类向量的转换