The C ++ function is followed by the const modifier and the const modifier.

Source: Internet
Author: User

The C ++ function is followed by the const modifier and the const modifier.

When declaring a member function, the const keyword is used to indicate that this function is a read-only function. That is to say, this function will not modify any data member (object ). To declare a const member function, place the const keyword behind the function brackets. The const keyword should be included in the declaration and definition.

Any function that does not modify data members should be declared as the const type. If the const member function is accidentally modified or other non-const member functions are called, the compiler will point out an error, which will undoubtedly improve the robustness of the program.

# Include <iostream> using namespace std; class temp {public: temp (int age); int getAge () const; void setNum (int num); private: int age ;}; temp: temp (int age) {this-> age = age;} int temp: getAge () const {age + = 10; // # Error... error C2166: l-value specifies const object # return age;} void main () {temp a (22); cout <"age =" <. getAge () <endl ;}
Because the const function is declared, no data member can be modified, but 10 is added to the age data member, so an error is generated.

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.