c++ - Constructing result in operator vs operating on default-constructed object -
i have class array labelled contents, , i'd define operators it. i'd in such way changing number of elements in class easy, expect future users change variables tracked, i'd ensure basic arithmetic operations on class efficient possible.
i can see 2 way of implementing operators. taking example of vector2d
class:
struct vector2d { //members const static int nelem = 2; double x; double y; //constructors vector2d() {} vector2d(double x, double y) : x(x), y(y) {} //operators double& operator[] (int index) { switch(index) { case 0: return x; case 1: return y; default: return std::out_of_range ("oops"); } } // option 1: operator+ constructing result vector2d operator+ (const vector2d & rhs) const { return vector2d(x + rhs.x, y+rhs.y); } // option 2: operator+ using loop , [] operator vector2d operator+ (const vector2d & rhs) const { vector2d result; for(int = 0; < nelem; i++) result[i] = (*this)[i] + rhs[i]; return result; } };
assuming use -03 optimization, there difference between 2 implementations of operator+
? understanding since default vector2d
constructor has no code body , class contents default data type, there no overhead in option 2 calling default constructor on result
before setting members. expect 2 equivalent, i'm not confident enough in knowledge sure.
your method won't work @ all. if want able change nelem
can't use x
, y
names. why? because changing nelem
3 won't magically add z
. , since can't for
loop on x
, y
, definition of nelem
meaningless.
finally, textbook case use of number template. create vector templated on how many elements has.
do this:
template<unsigned int len> class vector{ double v[len]; public: vector operator+(const vector &o){ vector res; (unsigned int i=0;i<len;++i) // -o3 , small len unrolled res.v[i]=v[i]+o.v[i]; } // ... etc. };
then use this:
vector<2> my_2d_vec; vector<3> my_3d_vec;
Comments
Post a Comment