Reputation: 29
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?
Upvotes: 0
Views: 56
Reputation: 4255
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];};
}
Upvotes: 4