簡體   English   中英

c ++ - 在一個對象上運行,運算符重載()與索引

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM