سؤال

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];
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

double b = some_obj[7][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.

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.

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);

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.

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top