Home > Software engineering >  No operator "[ ]" matches these operands C
No operator "[ ]" matches these operands C

Time:12-04

const DayOfYearSet::DayOfYear DayOfYearSet::operator[](int index){

        if(index < 0){
            
            cout << "Error! Index cannot be negative.." << endl;
            exit(1);
        }

        if(index >= _size){

            cout << "Error! Index overflows the array size.." << endl;
            exit(1);
        }

        return _sets[index];
    }

    const DayOfYearSet DayOfYearSet::operator (const DayOfYearSet &other){

        vector <DayOfYear> temp;
        for(auto i = 0; i < other.size();   i){
            temp.push_back(other[i]);
            .
            .
            .


        }
    }

Hey, I have an issue in the temp.push_back(other[i]) line of the code which the compiler says no operator "[]" matches these operands. As you can see I overloaded the index operator as member function but its not working? What am I doing wrong here? Thanks in advance..

EDIT: _sets is DayOfYear* _sets as a private data member of the class DayOfYearSet.

CodePudding user response:

You are trying to use operator[] on const DayOfYearSet &other, but that function is defined to only work on objects that are not const.

You should correctly const-qualify this function.

const DayOfYearSet::DayOfYear DayOfYearSet::operator[](int index) const
//                     This function can be used on const objects ^^^^^
  • Related