what is the best and how declare const in function of c++ -
i have these code
#include <iostream> using namespace std; class ex; class exx; class ex { public: int _val; int const *_p_val; void setptrval(int * const &val) { _p_val=val; } }; class exx { public: ex const *_ex; void setex(ex const &ex) { _ex=&ex; } }; int main() { ex x; int i=10; x.setptrval(&i); exx xx; xx.setex(x); int y=20; cout<<*(xx._ex->_p_val)<<endl; x.setptrval(&y); cout<<*(xx._ex->_p_val)<<endl; cout<<*x._p_val<<endl; return 0; }
1: can see, ex x not const of ex class. , ex const *_ex; pointer point ex const. why above ok?
2: const in void setex(ex const &ex) means can't modify ex in function body?
3: how fix setter function member pointer variable if want prototype above (suppose sercurity reason)?
ok. if ex const *_ex; become ex *_ex; so, in setter function, want prototype not modify argument object, above. how function body become?
a pointer (or reference)
const
not have pointconst
object. means can't used modify object points to; can safely point eitherconst
or non-const
object.yes. specifically, means reference passed function argument can't used modify object.
it's better include
const
if don't need use modification. prevent accidental modification, , allow pointconst
objects.
Comments
Post a Comment