overload operator & to produce sum of int[][]

Viewed 112

it's a test from some company.

overload & to return sum of int[][]

main()
{
    int arr[5][5];
    // initialization
    cout << &arr; // output the sum of arr
}

I try this code but returns compile error:

long operator &(int** arr)
{
    // return the sum of arr
}

error: the argument should contains class type or enumeration currently I understand this error, but how to overload operator for buildin types?

2 Answers

Example of overloading operator &, only for educational use! I would NOT recommend overloading operator& in any serious code.

#include <iostream>

struct my_array
{
    my_array()
    {
        for (int i = 0; i < 5; ++i)
        {
            for (int j = 0; j < 5; ++j)
            {
                values[i][j] = 1 + i + j;
            }
        }
    }

    int operator&()
    {
        int sum = 0;
        for (int i = 0; i < 5; ++i)
        {
            for (int j = 0; j < 5; ++j)
            {
                sum += values[i][j];
            }
        }

        return sum;
    }

private:
    int values[5][5]{};
};


int main()
{
    my_array m;
    int sum = &m;
    std::cout << sum;
}

I think interviewer may want you to overload operator<< actually, not & and the solution could then be like below. See it live here.

#include <iostream>

using int5x5_t = int[5][5];

std::ostream& operator<<(std::ostream& os, const int5x5_t* parr) {
  long sum = 0;
  for (auto& vec : *parr) {
    for (auto val : vec) {
      sum += val;
    }
  }
  return os << sum;
}

int main() {
  int arr[5][5] = {
    {0, 1, 2, 3, 4},
    {0, 1, 2, 3, 4},
    {0, 1, 2, 3, 4},
    {0, 1, 2, 3, 4},
    {0, 1, 2, 3, 4}
  };
  std::cout << &arr << std::endl;
}
Related