How can i overload the subscript operator with more than i dimension? if possible give an example.. pls dont ignore

Showing Answers 1 - 2 of 2 Answers

prashantha shet

  • Oct 7th, 2007
 

If your question is about how to write an operator overload with multiple dimensions, then you can overload operator (). The [] operator is a binary operator with an implied "this". This means you can pass in only one argument.

Now, what happens if you pass in multiple arguments to [] invocation?


Say you have


class C

{

public:

int operator [] (int i) { return i; }

}


now, if you write:

C c;

c[1,2,3]; //this is still valid


However, tThe value of 'i' passed into operator [] is 3. That is because, remember that ','(comma) is a valid operator in C++ and it resolves to the rightmost expression. In this case, the result of the expression "1,2,3" = 3. Therefore, c[1,2,3] will return "3".


On the other hand, there is no limit for the number of arguments for () operator. You can have a member function above like this:


int operator() (int i, int j, int k) { return i+j+k; }


In fact, you can also use varargs with this operator, as follows:


int operator() (int i, ...);


Hope that helps.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions