2017-06-22 73 views
3

我有个类来表示二维阵列和我想使用()例如操作员,C++ - 在物体上运行,操作符重载()具有索引

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

如何我可以重载()运算符可以访问数组元素

谢谢!

回答

7

你需要建立类似

int& operator()(int m, int n)

它返回一个参考数组元素,你可以通过向主叫网站,参考修改。

不要忘记建立const超载

const int& operator()(int m, int n) const

这样你就可以在调用点为一个const对象元素访问使用类似的语法。


最后,对于你的赋值运算符,你不应该让它const(你做p mutable?),你应该回到自己的参考,帮助复合赋值

Array& operator=(const Array& other){ 
    // Your existing code 
    return *this; 
} 

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

+0

@Quentin:谢谢你整理这混乱。 – Bathsheba

+1

任何人都注意到之前一个小时六个upvotes。尼斯:p – Quentin

+0

@Quentin:你看,所有这些批评都是完全没有根据的。 – Bathsheba