【问题标题】:selfmade vector template operator[] error自制矢量模板运算符[]错误
【发布时间】:2015-06-27 09:50:59
【问题描述】:

我已经制作了自己的矢量模板,operator[] 的一部分:

template <class T>
T& vector<T>::operator[](unsigned int index)
{
    return m_Data[index];
}

我在类复制构造函数中使用这段代码

Track::Track(const Track& src)
{
    for(unsigned int i = 0; i < src.sorted.size(); i++)
        AddCar(src.sorted[i]->rz, src.sorted[i]->owners.back()->name, src.sorted[i]->owners.back()->surname);
}

我收到一个错误'no match for operator[] (operands types are const vector&lt;Track*&gt; and unsigned int)'

我试图用const 关键字重载operator[]

const T& operator[](unsigned int);

但这给了我一个不同的错误:const T&amp; operator[](unsigned int); cannot be overloaded

这可能是什么原因?

【问题讨论】:

  • 另一个错误是什么?
  • 我猜当您将 const modifier 添加到您的 operator[] 时,您应该返回 const T&amp;,这是您的第二个错误
  • 我试过这个 const T& operator[](unsigned int);编译器说“const T& operator[](unsigned int); 不能重载”
  • @lllook ...当您将 const 修饰符添加到您的 operator[]...

标签: c++ vector operator-overloading


【解决方案1】:

原因正是您所说的:没有const 过载,因此您不能将[] 应用于const 向量。

你没有说你尝试了什么或错误是什么,但这应该有效:

T const & operator[](unsigned int index) const {return m_Data[index];}    
T       & operator[](unsigned int index)       {return m_Data[index];}

【讨论】:

    【解决方案2】:

    您必须像这样实现operator[]const 版本:

    template <class T>
    const T& vector<T>::operator[](unsigned int index) const
    {
        return m_Data[index];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 2010-10-18
      • 2011-03-01
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多