c++ - 如何重载下标运算符 [] 以引用 2d STL 数组?
问题描述
我正在尝试为我的类创建一个重载运算符,我的类包含一个二维数组容器。我想按如下方式使用运算符: fooClass a; a[i][j] = 4; 我不想像 a[i, j], a(i, j) 那样使用它,也不想调用函数来输入或输出元素。有可能吗?
链接调用不起作用,因为第一个返回指向数组的指针,第二个应该返回数组中的一个元素,即浮点数。
我的课看起来像这样:
class foo
{
public:
foo();
~foo();
foo& operator=(const foo&rhs);
foo& operator=(const foo&&rhs);
foo& operator=(std::initializer_list<std::initializer_list<float>> il);
friend std::ostream& operator<<( std::ostream& os, const foo&rhs);
std::array<float, 3>& operator[](const int & rhs); <<<<HERE<<<< What should it return?
private:
std::array<std::array<float, 3>, 3> matrix;
};
int main()
{
foo a;
a = {{1,2,3},{4,5,6},{7,8,9}};
a[1][2] = 13;
cout << a[1][2] << endl;
return(0);
}
我的问题是,如何做到这一点,函数应该..... operator[](const int & rhs);
返回什么?
仅供参考,我没有直接使用数组容器,因为我正在实现其他功能,我也在做矩阵列专业。
解决方案
这不行吗?
std::array<float, 3>& operator[](const int & rhs) {
return matrix[rhs];
}
推荐阅读
- react-native - 离线时如何使用 React Native 应用程序存储数据?
- marklogic - 如何找出导致集群重启的错误查询?
- makefile - 是否可以生成包含在 posix makefile 中的文件?
- r - 获取每组 dplyr 的相对丰度
- visual-studio-code - VSCODE 状态栏颜色是固定的
- typescript - 从泛型类型中删除构造函数签名(或调用签名)
- r - 如何通过一长串依赖关系自动安装 CRAN 包所依赖的 Bioconductor 包?
- javascript - 如果未加载,如何摆脱损坏的图像?
- java - 在应用程序中加载 .mp3 文件名时出错,显示错误我找不到
- salesforce - DocuSign 电子邮件资源文件未更新