【问题标题】:C++ Vector Template operator []C++ 向量模板运算符 []
【发布时间】:2012-09-29 23:34:42
【问题描述】:

首先我想说这是一项硬件任务,我只是对我面临的错误有疑问

我制作了一个带有插入函数的向量模板,该函数将 data_type 添加到动态数组的末尾。这是我目前拥有的。

// Insert the value at the specified index by moving the tail
// when Size = Capacity the Vector has to be reallocated first 
// to accomate the new element
void Insert(const DATA_TYPE& value, int index){

    // If the Capacity is not large enough then ...
    // allocate large vector
    if (Size >= Capacity){
        // 0. Let's boost the capacity
         Capacity += CAPACITY_BOOST;
        // 1. Allocate new larger vector
         DATA_TYPE* newData = new DATA_TYPE[Capacity];

        // 2. Copy from old Data into the newData
         for( int i=0; i< Size; i++)
                newData[i] = Data[i];

        // 3. Delete the old Data
         delete[] Data;

        // 4. Replace old Data-pointer with the newData pointer
        Data = newData;
    }

    // Move the tail
    for(int i=index; i<Size;i++){
        Data[i+1] = Data[i];
    }

    // Insert
    Data[index] = value;
    Size++;

}
DATA_TYPE& operator[] (int index) const{
    return *this[index];
}

注意:使用私有变量:Size、Capacity、Data(存储动态数组) 我很确定我已经正确实现了 add 或 push_back 函数。问题是,当我尝试 cout 诸如“cout

while compiling class template member function 'int &Vector<DATA_TYPE>::operator [](int) const'
      with
      [
          DATA_TYPE=int
      ]
see reference to class template instantiation 'Vector<DATA_TYPE>' being compiled
     with
     [
          DATA_TYPE=int
      ]
error C2440: 'return' : cannot convert from 'const Vector<DATA_TYPE>' to 'int &'
    with
     [
        DATA_TYPE=int
      ]

【问题讨论】:

  • 每个帖子请坚持1个问题。
  • 抱歉,谢谢提醒

标签: c++ vector operator-keyword ostream


【解决方案1】:

operator[] 函数被声明为常量,即它不能更改 Vector 对象中的任何内容。但是它返回一个引用,这意味着返回的值可以被修改。这两者相互矛盾。

这可以通过从函数末尾删除const 或不返回引用来解决。

【讨论】:

  • 这不是 OPs 代码的问题。这可能不是一个好的做法,但它不是一个实际的错误(至少在正确实现 operator[] 时)。
【解决方案2】:

你的operator[]应该有2个版本:

const DATA_TYPE& operator[] (int index) const;
DATA_TYPE& operator[] (int index);

你所拥有的是两者的奇怪组合。

你也应该回来

return Data[index];

返回(*this)[index]; 会导致无限递归调用(嗯,不是无限的,在此之前你会得到一个stackoverflow)。

【讨论】:

  • +1 你能解释一下无限递归部分吗?我想我没有完全理解它。
  • @Mahesh sure - (*this)[index] 相当于直接调用operator[](index),它会一次又一次地调用自己。
  • 哦该死我被重新启动了,我以前有过,但是当我调用我的函数以通过 cout 显示时,我试图显示错误的索引(即 a[1] 而不是 a[0])并假设它必须更改为 *this[index]。我觉得很笨-_-。无论如何,谢谢。
【解决方案3】:

这里有三个问题:

  1. 运算符优先级。 *this[index] 被解析为 *(this[index]),而您的意思是 (*this)[index]
  2. 您正在从 const 方法返回对您的数据的可变引用。
  3. operator[] 的定义是循环的。在operator[] 中返回(*this)[index] 会导致无限递归。

【讨论】:

  • 从技术上讲,从该运算符返回可变引用并没有错(因为该引用是指向由对象中的指针寻址的数据,所以数据本身不是 const)。这是否是好的做法可能值得商榷,并且取决于用例,但我不会称之为问题
  • @Grizzly:不过,我不认为这是老师所期望的。
  • 我真的不想推测这一点(根据我的经验,方法签名通常在此类练习的作业中给出)。这就是为什么我会称这是一个有用的建议,而不是一个没有读者解释它的问题,因为你不能这样做。
猜你喜欢
  • 2020-06-25
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多