Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++'s operator[] take more than one argument?

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];
like image 718
Dan Avatar asked Nov 29 '22 04:11

Dan


2 Answers

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.

like image 69
Praetorian Avatar answered Dec 05 '22 03:12

Praetorian


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

double b = some_obj[7][3];
like image 28
Andrea Bergia Avatar answered Dec 05 '22 03:12

Andrea Bergia