const modifier after C + + function

Source: Internet
Author: User

When declaring a member function, the const keyword is used to indicate that the function is a "read-only (read-only)" function, which means that the function does not modify any data member (object). To declare a const member function, place the const keyword after the function bracket. The const keyword should be placed when declaring and defining.

Any function that does not modify a data member should be declared as a const type. If you inadvertently modify the data member when you write the const member function, or if you call other non-const member functions, the compiler will indicate the error, which will undoubtedly improve the robustness of the program.

#include <iostream>using namespacestd;classtemp{ Public: Temp (intAge ); intGetage ()Const; voidSetnum (intnum);Private:    intAge ;}; Temp::temp (intAge ) {     This->age =Age ;}intTemp::getage ()Const{ Age+=Ten;//#Error ... Error c2166:l-value specifies const object #    returnAge ;}voidMain () {Temp A ( A); cout<<"age="<< a.getage () <<Endl;}
Because the const function is declared, no data member can be modified, but here the age data member is added 10, resulting in an error.

const modifier after C + + function

Related Article

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.