4

Is it possible to define an overloaded operator[] that takes more than one argument? That is, can I define operator[] as follows:

  //In some class
  double operator[](const int a, const int b){
     return big_array[a+offset*b];}

and later use it like this?

double b=some_obj[7,3];
Dan
  • 11,525
  • 12
  • 49
  • 79

7 Answers7

7

No you can't overload operator[] to take more than one argument. Instead of

double b = some_obj[7,3];

use

double b = some_obj[7][3];

This answer explains how to create a proxy object to be able to the latter.

Otherwise, you could just overload operator() to take 2 arguments.

Community
  • 1
  • 1
Praetorian
  • 103,386
  • 18
  • 232
  • 318
  • 3
    Even better (in my opinion, at least): make a function "get", "at" or something like that, with two arguments. In most cases, it will make the code clearer than overloading operator (). – Andrea Bergia Aug 11 '11 at 21:29
6

No. The idiomatic way to do that in C++ is

double b = some_obj[7][3];
Andrea Bergia
  • 5,375
  • 1
  • 24
  • 38
  • 2
    Though that's not necessarily the best way, it requires somewhat awkward proxy classes if you do it properly. Depending on what you actually want it can be more straightforward to just use `operator()` with two arguments. – leftaroundabout Aug 11 '11 at 21:05
3

No, C++ syntax says that in

double b=some_obj[7,3];

the comma is the comma operator, not the comma that separates arguments.

john
  • 72,145
  • 4
  • 50
  • 71
2

Bottom line: No, don't confuse your users.

From C++ FAQ:

Remember the purpose of operator overloading: to reduce the cost and defect rate in code that uses your class. If you create operators that confuse your users (because they're cool, because they make the code faster, because you need to prove to yourself that you can do it; doesn't really matter why), you've violated the whole reason for using operator overloading in the first place.

2

You could do what Andrea suggested, or you could overload operator() to take two arguments:

// In some class
double operator()(const int a, const int b) {
    return big_array[a + offset * b];
}

// Then use it like this:
double b = some_obj(7, 3);
Seth Carnegie
  • 72,057
  • 21
  • 174
  • 247
1

The better way to do that, since it doesn't lock you into creating temporaries and allows multiple arguments, is operator(). More details are in the C++ FAQ.

ChrisV
  • 3,313
  • 15
  • 19
1

You can't, but in this case I think a function would be better since it is not intuitive what your operator is doing.

Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609