实现类似字符串的类时"no type named 'const_reference' "错误

"no type named 'const_reference' " error when implementing a string-like class

本文关键字:错误 reference const type 字符串 实现 no named      更新时间:2023-10-16

我正在尝试实现与std :: string相似行为的类,并且我在std ::复制行中收到错误:

Str& operator+=(const Str& s){
    std::copy(s.data.begin(), s.data.end(), std::back_inserter(data));
    return *this;
}

'数据'是Vec&lt类型的对象;char>,而vec是我自己实施的类似矢量的类别,似乎自己工作正常。

它也说:

c: mingw bin .. lib gcc gcc mingw32 3.4.2 ............................................ include c 3.4.2 bits stl_iterator.h ||:: back_insert_iterator<Vec<char>>':|

听起来您的 vec不符合容器要求,因此不能保证与容器一起使用的标准设施(例如back_inserter)可用。

C 11中的表96中指定了要求,尽管C 98中的表65可能更适合您的古代编译器。这些要求之一是嵌套的const_reference类型。

检查std::back_inserterstd::copy的要求。尤其是,std::back_inserter期望一个可以满足概念容器的参数。至少这意味着实施标准的§23.2.1,其中列出的一个要求之一是:

X::const_reference |T的const lvalue |编译时间

即。容器类型中的typedef const_reference

back_inserter是一种说服力函数,可在容器上构造back_insert_iterator;在这种情况下,data

data,您已经说过是您自己的本地 vector -type类。为了使此工作起作用,您的vector类必须具有const_reference Typedef定义。这样的东西:

template <typename Item>
class Vec
{
public:
  typedef const Item& const_reference;
};

任何实现容器的其他要求。这些在C 03标准中概述,在 23.1中的容器需求中,包括表65。

另请参阅此问题以讨论要求。

尝试添加

typedef t value_type;
typedef const value_type&amp;const_reference;

在您的vec&lt; t>身体中。

问题需要更多细节,例如您的VEC类。

您遇到的错误到底是什么?请分享有关错误的更多信息。控制台日志会有所帮助。

std ::复制带有两个输入迭代器。(http://www.cplusplus.com/reference/algorithm/copy/)您确定像班级一样的向量是否正确处理迭代器?

另外,请检查您的VEC是否支持Back_inserter所需的容器要求。http://www.cplusplus.com/reference/eriterator/back_inserter/

相关文章: