Wednesday 15 August 2012

c++ - Method questions - What changes the value and what doesn't? What's invalid? -



c++ - Method questions - What changes the value and what doesn't? What's invalid? -

i have homework question

what  does  v  contain  after  these  methods  and  why?  if  the  method  is  invalid,  explain  why.

template <typename t> void reset1(mathvector<t> v) {v[0] = 0;} template <typename t> void reset2(mathvector<t> &v) {v[0] = 0;} template <typename t> void reset3(const mathvector<t> &v) {v[0] = 0;}

my previous experience tells me first leave vector unchanged because it's not beingness passed value rather copy, sec changed properly, , 3rd invalid because parameter specifies const.

however i'm pretty sure in c++ arrays passed value because doesn't automatically invoke re-create constructor or anything. suspect might true of vectors i'm not sure. if case, first 1 alter vector , sec 1 invalid because you're trying operate on vector's pointer doesn't create sense? i'm not sure here

template <typename t> void reset1(mathvector<t> v) {v[0] = 0;}

this passes vector by value, modification vector v local only, , original vector unchanged 1 time function complete.

template <typename t> void reset2(mathvector<t> &v) {v[0] = 0;}

this passes vector by reference, changing first element modifying original vector. here first element have been changed 0.

template <typename t> void reset3(const mathvector<t> &v) {v[0] = 0;}

here vector passed by reference, const. means may not effort modify vector, should @ to the lowest degree produce compiler warning.

c++ templates methods vector const

No comments:

Post a Comment