c++ - 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?
解决方案
重载运算符 & 的示例,仅用于教育用途!我不建议在任何严肃的代码中重载 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;
}
推荐阅读
- amazon-web-services - 我如何知道计划的 Lambda 是否未执行?
- python - 是否可以从 Google Drive 自动将内容上传到 Cloud Storage?
- c# - 从字节数组加载图像的问题
- python - Python selenium 不点击?
- javascript - Electron、contextIsolation 和 contextBridge
- neo4j - 使用 Pearson 的 Neo4j 协作过滤 (CF) 推荐查询
- vim - vim 功能键映射在 Ubuntu 升级后不再工作
- kubernetes - 通过 GKE 上的“https”在自定义端口上公开服务
- java - 未创建休眠@OneToMany 连接表
- sql-server - 每 30 个连接中就有 1 个出现 Win32Exception:未知位置错误。Azure Web 应用程序到 AWS SQL DB