const - Accessor functions in class c++ -
for illustration have accessor function class:
class { public: int a; int& geta() const; }; int& a::geta () const { homecoming a; // error: invalid initialization of reference of type 'int&' look of type 'const // int' }
the questions are: 1. info fellow member 'a' not of type 'const int', why error? 2. when alter homecoming type int works. why?
because specify geta()
const
. returning non const
reference fellow member variable method declared const
allow modify value referenced.
if want read-only accessor declare accessor as
const int& a::geta() const
otherwise must remove constness method.
turning returned value int
allowed because not returning reference anymore, re-create of a
there no way modify original fellow member variable.
mind allowed have them both available:
int& geta() { homecoming a; } const int& geta() const { homecoming a; }
c++ const accessor
No comments:
Post a Comment