[英]c++ - run on an object, operator overloading () with index
I have a class to represent two-dimensional array and I want to use () operator for example, 我有一个类来表示二维数组,我想使用()运算符,例如,
Array arr;
arr(2,5) = 17; // I want to assign 17 as element in 2nd row and 5th column.
I tried something like that: (but is not working) 我试过这样的事情:(但是没有用)
void operator(int m, int n)(int num) {
int m, n;
p[m][n] = num;
}
i have an operator = (this working): 我有一个运营商=(这个工作):
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
class has T**
as private member. Array
类将T**
作为私有成员。
How can I overload ()
operator to access elements in array 我如何使用overload
()
运算符来访问数组中的元素
Thank You! 谢谢!
You need to build something like 你需要建立类似的东西
int& operator()(int m, int n)
which returns a reference to the array element, that you can modify through that reference at the calling site. 它返回对数组元素的引用 ,您可以通过调用站点上的引用进行修改。
Don't forget to build the const
overload 不要忘记构建
const
重载
const int& operator()(int m, int n) const
so you can use similar syntax at a call site for element access for a const
object. 因此,您可以在调用站点使用类似的语法来访问
const
对象的元素。
Finally, for your assignment operator, you ought not make it const
(have you made p mutable
?), and you should return a reference to self to help compound assignment : 最后,对于你的赋值运算符,你不应该使它成为
const
(你是否已经使p mutable
变为p mutable
?),并且你应该返回对self的引用以帮助复合赋值 :
Array& operator=(const Array& other){
// Your existing code
return *this;
}
Reference: http://en.cppreference.com/w/cpp/language/copy_assignment 参考: http : //en.cppreference.com/w/cpp/language/copy_assignment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.