[英]c++ - run on an object, operator overloading () with index
我有一个类来表示二维数组,我想使用()运算符,例如,
Array arr;
arr(2,5) = 17; // I want to assign 17 as element in 2nd row and 5th column.
我试过这样的事情:(但是没有用)
void operator(int m, int n)(int num) {
int m, n;
p[m][n] = num;
}
我有一个运营商=(这个工作):
void operator=(const Array& other) const {
for (int i = 0; i < DIM; i++) {
for (int j = 0; j < DIM; j++) {
p[i][j] = other.p[i][j];
}
}
}
Array
类将T**
作为私有成员。
我如何使用overload ()
运算符来访问数组中的元素
谢谢!
你需要建立类似的东西
int& operator()(int m, int n)
它返回对数组元素的引用 ,您可以通过调用站点上的引用进行修改。
不要忘记构建const
重载
const int& operator()(int m, int n) const
因此,您可以在调用站点使用类似的语法来访问const
对象的元素。
最后,对于你的赋值运算符,你不应该使它成为const
(你是否已经使p mutable
变为p mutable
?),并且你应该返回对self的引用以帮助复合赋值 :
Array& operator=(const Array& other){
// Your existing code
return *this;
}
参考: http : //en.cppreference.com/w/cpp/language/copy_assignment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.