gpt4 book ai didi

c++ - 重载运算符 & 以产生 int[][] 的总和

转载 作者:行者123 更新时间:2023-12-05 08:46:47 24 4
gpt4 key购买 nike

这是某公司的测试。

重载 & 以返回 int[][] 的总和

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

我尝试了这段代码,但返回了编译错误:

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

错误:参数应包含类类型或枚举目前我理解这个错误,但是如何为构建类型重载运算符?

最佳答案

重载运算符 & 的例子,仅供学习使用!我不建议在任何严肃的代码中重载 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;
}

关于c++ - 重载运算符 & 以产生 int[][] 的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69055746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com