jeudi 13 août 2015

Error code 2556,2040

I keep getting error code error C2556: 'int myArray::operator const' : overloaded function differs only by return type from 'int &myArray::operator const'

see declaration of 'myArray::operator []'

error C2040: 'myArray::operator []' : 'int (int) const' differs in levels of indirection from 'int &(int) const'

This is my myArray .cpp file

#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];
}

This is my program .cpp code

#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;
}

This is my myArray header:

#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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire