C ++ note (5) const and mutable keywords

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.