将 const 传递为这样时出错

Error Passing Const as this

本文关键字:出错 const      更新时间:2023-10-16

im正在为学校做一个项目,但有这个错误,但我无法弄清楚修复它:

错误:将"const xArray"作为"size_t xArray::P ushBack(int)"的"this"参数传递丢弃限定符[-fpermissive] a.回推(温度);

以下是错误来自的函数:

    istream& operator>>(istream& in, const xArray& a)
    {
          int temp;
          in >> temp;
          a.PushBack(temp);
          return in;
    }

这是我的PushBack代码:

    size_t xArray::PushBack(int c)
    {
            if(len == arraySize)
            {
                     int* temp = new int[arraySize* 2];
                     size_t i;
                     for(i = 0; i < arraySize; i++)
                     {
                            temp[i] = data[i];
                     }
                     delete [] data;
                     data = temp;
                     data[len+1] = c;
                     len = len + 1;
            }
            else
            {
                  data[len + 1] = c;
                  len = len + 1;
            }
    }

有关如何修复或解释此错误的任何帮助将不胜感激提前致谢

对于istream& operator>>(istream& in, const xArray& a)a被声明为 const,并且调用 PushBack() 将失败,因为xArray::PushBack()是一个非 const 成员函数。

您可以将a的参数类型更改为非常量引用,例如

istream& operator>>(istream& in, xArray& a)
{
    ...
}