-
June 9th, 2011, 10:03 PM
#1
Operator [] Overloading
Hello codeguru members,
I'm implementing an class to manipulate mathematical matrices and I want it to have an interface as close as mathematical notation as possible.
So here it is my question:
can I overload some kind of operator[][] ?
I would like to access elements like this:
matrix A(3,3);
cout << A[0][1];
Is this possible?
An solution could be an friend operator[] function that retuns another class, like the matrix_line, and then overloading [] again, this time returning the element, right? But i find this solution deselegant and unclear. Any ideas?
-
June 9th, 2011, 10:33 PM
#2
Re: Operator [] Overloading
Originally Posted by souza.vss
can I overload some kind of operator[][] ?
No.
Originally Posted by souza.vss
An solution could be an friend operator[] function that retuns another class, like the matrix_line, and then overloading [] again, this time returning the element, right? But i find this solution deselegant and unclear. Any ideas?
If you don't want to overload operator[] to return a proxy object for which operator[] is overloaded then overload operator() to accept two arguments.
-
June 10th, 2011, 08:37 AM
#3
Re: Operator [] Overloading
If you make operator[] return a pointer, than the second [] will work as it always does on pointers. However, this gives up the possibility of bounds-checking the second access.
Also, you should note that several well-respected libraries already provide a mathematical matrix class. For instance, Boost.uBLAS and Eigen.
Last edited by Lindley; June 10th, 2011 at 08:39 AM.
-
June 10th, 2011, 08:43 AM
#4
Re: Operator [] Overloading
Originally Posted by souza.vss
matrix A(3,3);
cout << A[0][1];
I think it would be better to use a template class, and aim for syntax like:
matrix<3,3> a;
cout << a(0,1);
-
June 13th, 2011, 10:08 PM
#5
Re: Operator [] Overloading
template <typename T>
class Row
{
public:
const T& operator []( int i);
//..........
};
template <typename T>
class <Martix>
{
public:
const Row<T>& operator []( int i);
//..........
};
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|