错误代码2556,2040

时间:2015-08-14 00:37:51

标签: c++

我一直收到错误代码 错误C2556:' int myArray :: operator const' :重载函数的区别仅在于' int& myArray :: operator const'

的返回类型

参见' myArray :: operator []'

的声明

错误C2040:' myArray :: operator []' :' int(int)const'间接水平与' int&(int)const'

不同

这是我的myArray .cpp文件

#include <iostream>
#include "myArray.h"

using namespace std;

myArray::myArray(int newSize)
{
    startIndex=0;
    size = newSize;
    PtrArray = new int[size];
    for(int i=0; i< size; i++)
        PtrArray[i] = 0;
}

myArray::myArray(int newStartIndex, int newSize)
{
    startIndex = -newStartIndex;
    size = newSize;
    PtrArray= new int [size + startIndex];

    for(int i=0; i< (size + startIndex); i++)
        PtrArray[i]= 0;
}

myArray::~myArray()
{
    delete [] PtrArray;
}

int &myArray::operator[] (int index)
{
    if ((index <-startIndex || index >= size))
    {
        cerr<<"Error: Index "<<index<<" is our of range"<<endl;
        system("pause");
        exit(1);
    }

    return PtrArray[index+startIndex];
}

int myArray:: operator[](int index) const
{
    if (index <-startIndex || index >= size)
    {
        cerr<<"Error:Index"<< index<<"isout of range"<<endl;
            system("pause");
            exit(2);
    }

    return PtrArray[index + startIndex];
}

这是我的程序.cpp代码

#include <iostream>
#include "myArray.h"

using namespace std;

int main()
{
    myArray list(5);
    myArray myList(2,13);
    myArray yourList(-5,9);

    for(int i=0; i<5; i++)
        list[i]=i*i;

    for(int j=2; j<13; j++)
        myList[j]=j*j;

    for(int k=-5; k<9; k++)
        yourList[k]=k*k;

    cout<<"The elements stored in the first object list are:"<<endl;

    for(int i=0; i<5; i++)
    {
        cout<<"list["<<i<<"[\t\t="<<list[i]<<endl;
    }

    cout<<"The elements stored in the second object myList are:"<<endl;

    for(int j=2; j<13; j++)
    {
        cout<<"myList["<<j<<"]\t="<<myList[j]<<endl;
    }

    cout<<"The elements stored in the third object yourList are:"<<endl;

    for (int k=-5;k<9;k++)
    {
        cout<<"yourList["<<k<<"]\t"<<yourList[k]<<endl;
    }

    cin>>yourList[-13];
    system("pause");
    return 0;
}

这是我的myArray标题:

#ifndef H_myArray
#define H_Array
#include <iostream>

using namespace std;

class myArray
{
public:
    myArray(int);
    myArray(int,int const);
    ~myArray();

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

private:
    int startIndex;
    int size;
    int *PtrArray;


};

#endif

1 个答案:

答案 0 :(得分:2)

您的声明与实现不匹配。您将函数声明为:

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

您将它们实现为:

int &operator[](int) { ... }
int operator[](int) const { ... }
   ^^^ Missing &

您可以修复声明或实现。我的建议是修改声明。

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