0

in my class we are going through operator overloading in c++. I am working on one of our practice problems to help us learn the basics of overloading and using friend functions. This is the first problem which asks me to overload an operator that my professor didn't provide already written. The prompt is to write a function which can access testScores inside of the Marks class via cout << Sam[int] << endl;. I believe the way to do this would be to overload teh [] operator to output testScores[int] but I may be incorrect. I am trying to write the overload function, but I am getting an error which says that operator[] must be a member function, which it is as far as I can tell. I am not 100% sure that the way I am implementing the overloading function will work, but I cannot test it anyway until I find out what I have done wrong for visual studio to not see that I have it included as a member.

This is the class:

#pragma once
#include<iostream>
using namespace std;
class Marks
{
private:
    int testScores[3];
public:
    Marks();
    Marks(int, int, int);
    friend int& operator[](int, Marks&);///here it says operator[] must be a member function
};

Here is how I am trying to implement the overloading function:

int& operator[](int index, Marks& p) {
    int temp;
    temp = p.testScores[index];//I cannot access testScores because it says operator[] isn't a member of Marks. 


    return temp;
}

The above implementation may not work but I obviously am having a problem besides that right now.

This is what the actual prompt asks me to do: In the following class object instantiation how you write the class Marks both header and implantation to output the private variable tesctScores[3] of Sam in the following way.

using this provided int main code:

int main(){
Marks Sam(99, 100, 89);
cout<<Sam[0]<<endl;
cout<<Sam[1]<<endl;
cout<<Sam[2]<<endl;
}

Is it not possible to overload [] and I should instead try overloading << ? I would think the overloading there would cause problems with endl;. Anyone's input on why visual studio does not detect that my overloading function is a member of class Marks?

  • "why visual studio does not detect that my overloading function is a member of class Marks?" You made it a `friend`. A friend is not a member. – Ben Voigt Apr 27 '20 at 01:43
  • @BenVoigt even when I don't use the friend keyword and I implement it in the same fashion as the other public members I get the same error – killerkody gaming Apr 27 '20 at 01:49

1 Answers1

2

Operator Overloading

a[b] (a).operator[](b) cannot be non-member

So the compiler saying you operator[] must be a member function is absolutely correct. You need to overload operator[] in the class.

class Marks
{
private:
    int testScores[3];
public:
    Marks();
    Marks(int, int, int);
    int& operator[](std::size_t idx);
};

int& Marks::operator[](std::size_t idx) {
  return testScores[idx];
}
273K
  • 29,503
  • 10
  • 41
  • 64