0

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.

1
  • did you tried int& operator()(int x, int y); Commented Dec 10, 2015 at 9:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.