Re: overloading the [] operator in a vector child class
Hi
y-man wrote:
I am creating a child class of the vector, which contains a couple of
functions to make the work with carthesian coordinate vectors easier.
To make things work more easily, I would like to be able to access the
vector through a string which is either x, y or z.
[...]
My class is now:
class xyzvec : public vector<double> {
It should probably read "std::vector<double>".
Deriving publicly from std::vector is a bad idea if you impose
additional restrictions. In your case, you want the vector to always be
of size three. But one could easily do:
xyzvec x;
std::vector<double> y; // empty vector
y.swap(x); // hell breaks loose
Why don't you just use three member doubles?
double x() { return (*this)[0] ; }
double y() { return (*this)[1] ; }
double z() { return (*this)[2] ; }
Personally, I would prefer const and non-const versions returning const
references and non-const references, respectively.
double length( void ) {
double n = pow(pow((*this)[0],2) + pow((*this)[1],2) + pow((*this)
[2],2),0.5) ;
return std::sqrt( x()*x() + y()*y() + z()*z() );
is more readable in my opinion (and likely to perform better)
return n;
}
double& operator[] (const string&) {
if(string=="x") return &(*this)[0] ;
if(string=="y") return &(*this)[0] ;
if(string=="z") return &(*this)[0] ;
}
1. string is a type (I hope... you never included <string> and said you
were using std::string), not an object...
2. You declare operator[] to return a reference, but you actually try to
return pointers
3. You return the same pointer in any case.
private:
} ;
why "private:" if nothing follows?
Markus