Hyftar
Hyftar

Reputation: 167

C++ overloading operator() for assignation

I was making a Matrix class and I wanted to override the operator() so I can assign numbers to specific places in my matrix like so:

int a[6] = { 1, 2, 3, 4, 5, 6 };
Matrix2d<int> blah(2, 2, a);
blah(2, 2) = 7;

What is not working right now is the 3rd line, how can I overload the () operator correctly so it works? (if there's even a way to do it) The matrix contains a 1d array so the value would have to be set at the correct place.

Upvotes: 0

Views: 106

Answers (2)

Nyashes
Nyashes

Reputation: 652

you can use references to achieve that

class myClass {
    int m_v1, m_v2, m_v3;
public:
    int &/*that's the important character*/ returnRef(int number) {
        switch (number) {
            case 1: return m_v1;
            case 2: return m_v2;
            case 3: return m_v3;
        }
    }
    void print() const { std::cout << m_v1 << " " << m_v2 << " " << m_v3; }
}

and then:

myClass a;
a.returnRef(1) = 3;
a.returnRef(2) = 2;
a.returnRef(3) = 1;
a.print(); //print "3 2 1"

note that references "look like" pointers with more restrictions don't return references to local/deleted variables.

more informations about returning references here: http://www.tutorialspoint.com/cplusplus/returning_values_by_reference.htm

Upvotes: 0

TartanLlama
TartanLlama

Reputation: 65620

Just return a reference to the element:

T& operator() (std::size_t x, std::size_t y);

Assuming that T is the template parameter to Matrix2d and the arguments are both of type std::size_t.

Upvotes: 2

Related Questions