0
votes
#include <iostream>

using namespace std; 

class my_array_over
{

  size_t len = 1;

  int *a = new int[1];

public:
  my_array_over() { a[0] = 0; }

  my_array_over(size_t ln, const int *o) : len(ln), a(new int[ln])

  {
    for (size_t n = 0; n < ln; ++n)
      a[n] = o[n];
  }

  ~my_array_over() { delete[] a; }


  size_t get_length() const
  {
    return len;
  }

  int get(size_t n) const
  {
    return a[n];
  }

  int set(size_t n, int v)
  {
    int tmp = a[n];
    a[n] = v;
    return tmp;
  }

};

void foo(const my_array_over &a2, size_t i)
{

  if (i < a2.get_length())

    std::cout << a2[i] << std::endl;
}

Been trying to fix this code but kept getting an error saying "no match for 'operator[]'enter code here(operand types are 'const my_array_over' and 'size_t' {aka 'long unsigned int'})" on

std::cout << a2[i] << std::endl;

1
The my_array_over class does not have an operator[] method.Eljay

1 Answers

0
votes

In this statement

std::cout << a2[i] << std::endl;

there is used the subscript operator for an object of the type my_array_over that (the subscript operator) is not defined within the class. It seems you mean

std::cout << a2.get( i ) << std::endl;

Otherwise you need to define the subscript operator within the class definition. For example

const int & operator []( size_t n ) const
{
    return a[n];
}

int & operator []( size_t n )
{
    return a[n];
}