使用模板类复制构造函数时出错

时间:2019-06-15 06:53:44

标签: c++ templates vector copy-constructor implementation

我不能写副本构造函数。如何解决该错误?

试图像这样修复它:

template<typename T, typename A>
vector<T, A>::vector(const vector<T, A> &other)
{
    this->allocator_ = other.allocator_;
    this->size_ = other.size_;
    this->space_ = other.space_;
    this->data_ = other.allocator_.allocate(other.space_);

  std::copy(other.data_, other.data_ + other.size_, this->data_);
}
template <typename T, typename A = std::allocator<T>>
struct vector_base
{
  A    allocator_;
  int  size_;
  int  space_;
  T*   data_;

  vector_base(A const& alloc, int n)
      :allocator_(alloc)
  {
    if (n > 1)
    {
      data_ = allocator_.allocate(n); size_ = 0, space_ = n;
    }
    else
    {
      data_ = allocator_.allocate(8); size_ = 0, space_ = 8;
    }
  }

  ~vector_base() {allocator_.deallocate(data_, space_);}
};
class vector : protected vector_base<T, A> 
{
  vector(vector<T, A> const &v);
  vector<T, A>& operator=(vector<T, A> const &v);
};

template<typename T, typename A>
vector<T, A>::vector(const vector<T, A> &other)
  : allocator_(other.allocator_), size_(other.size_), space_(other.space_), data_(other.allocator_.allocate(other.space_))
{

  std::copy(other.data_, other.data_ + other.size_, this->data_);
}

template<typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector<T, A> const &v)
{
  if (this != &v)
  {
    vector<T, A> copy_vector(v);
    copy_vector.swap(*this);
  }
  return *this;
}

错误:类“ vector”没有任何名为“ allocator_”的字段    :allocator_(other.allocator _),size_(other.size _),space_(other.space _),data_(other.allocator_.allocate(other.space _))

0 个答案:

没有答案