[英]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.