C ++ note (5) const keyword
1. Const A fun2 (); const A * fun3 ();
Returns the const variable.
2. Use of const in class member functions
Generally placed behind the function body, such as void fun () const;
Any function that does not modify data members is declared as const type. If the const member function is accidentally modified or other non-const member functions are called, the compiler reports an error, which greatly improvesProgramRobustness.
3. Const variable
4. Const object
Only the const member variables and const member functions can be accessed.
This interview question is said to exist:
Class A
{< br> Public:
char get_m () const
{< br> return m;
}< br> PRIVATE:
char m;
}< br> change the m value in the get_m function.
I think we have to use hooligans for this kind of hooligans:
Char get_m () const
{
Char * P = (char *) & M;
* P = 'C ';
Return m;
}
Yes, because the const function in the class is implemented by "taking all the members in the class as const.
But this is my "rogue programmer" approach.
In fact, the mutable modifier should be used as instructed by colleagues:
Mutable char m;
In this way, even in the const function of the class, the M type can be changed.
In addition, if you want to skip this job, you can also write as follows:
# Define const
Haha, then the interviewer will not dare to ask you. : D
Refer:
Http://dulao5.blog.hexun.com/6687190_d.html