I want to define a class myVector that support both assignment operator=
and bracket access e.g myclass(1) = 0.5
. See a dummy example below
class myVector
{
public:
vector<double> _v;
myVector(unsigned int size) : _v(size, 0) { }
double& operator()(int i)
{
return _v[i];
}
unsigned int size() const { return _v.size(); }
myVector& operator=(const myVector& v)
{
_v.resize(v.size());
for(int i=0;i<v.size();i++)
_v[i] = v(i);
}
}
This code cannot be compiled since ()
is not defined as a constant function. This is because I want to enable direct assignment such as myvector(1) = 2
. To solve this problem, I can only think of two solutions. One is to define sth. like double getValue(int i) const
but this seems weird since some duplicate code is added. The other is to remove const
from the signature of ()
function, but that is undesirable as well. I am sure there will be a good work around but I cannot find it.