c ++ - 在一个对象上运行,运算符重载()与索引

时间:2017-06-22 12:52:35

标签: c++ operators

我有一个表示二维数组的类,我想使用()运算符,例如

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**作为私人会员。

如何重载()运算符以访问数组

中的元素

谢谢!

1 个答案:

答案 0 :(得分:7)

您需要构建类似

的内容

p-autoComplete

引用返回给数组元素,您可以在调用站点通过该引用进行修改。

不要忘记构建int& operator()(int m, int n)重载

const

因此您可以在调用站点使用类似的语法来访问const int& operator()(int m, int n) const对象的元素。

最后,对于你的赋值运算符,你不应该使它const(你有const吗?),你应该返回对self的引用以帮助复合赋值

p mutable

参考:http://en.cppreference.com/w/cpp/language/copy_assignment