0

Is it possible to make a structure mimic one of its elements? Example:

struct example_struct
{
  double x[2];
  double operator[](int i){return x[i];};
}
struct example_struct var;

Now, assuming var.x has somehow been initialised, expressions like std::cout<<var[1]; clearly work, but what should I do to make expressions like var[1]=3; work?

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • 1
    Make your return type `double&` and find a [solid C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – scohe001 Oct 16 '17 at 17:49
  • http://www.learncpp.com/cpp-tutorial/98-overloading-the-subscript-operator/ – zzxyz Oct 16 '17 at 17:52
  • `struct example_struct var;` is C. You don't need struct here. –  Oct 16 '17 at 17:56

1 Answers1

4

You need to return a reference, not a copy in order for var[1]=3 to work.

struct example_struct
{
   double x[2];
   double& operator[](int i) return x[i];};
}
scohe001
  • 15,110
  • 2
  • 31
  • 51
lcs
  • 4,227
  • 17
  • 36