首页 > 解决方案 > overload operator & to produce sum of int[][]

问题描述

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?

标签: c++operator-overloading

解决方案


重载运算符 & 的示例,仅用于教育用途!我不建议在任何严肃的代码中重载 operator&。

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

推荐阅读