简体   繁体   中英

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.

How can I overload () operator to access elements in array

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 int& operator()(int m, int n) const

so you can use similar syntax at a call site for element access for a const object.


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 :

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

Reference: http://en.cppreference.com/w/cpp/language/copy_assignment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM