1? The member function can be declared as a const function (after the declaration is added const)
2? For const objects, only const member functions can be called3? const functions and non-const functions can form overloads4? Non-const member functions are preferred for function calls to non-const objects5? For mutable data members in a class, they can be modified by the const member function
main.cpp//const////Created by, on 15/1/24.//Copyright (c) 2015 Huangyongrui. All rights reserved.//#include <iostream>using namespace std;//Employee class employee{string name; int age; mutable int x;//Note the role of this keyword, oh Public:employee (String Name,int Age): Name (name), and the "(age) {///name = name;//) is not separated }//void SetName (string name) {this->name = name; } string GetName () const{return name; } void Show () {cout << name << "This year" << age << "old" << Endl; Name = "2345"; #pragma note that the const is added in front, decorated with a return value of const void Show1 () {cout << name << "This year" << age << "old A "<< Endl; Name = "2345"; } #pragma we want to modify a function to make it constant, you should add the const to the argument void Show2 () const{cout << name << "This year" << age << "years old" << Endl; This->name = "1234567"; the//const function cannot modify the normal member variable x = 100;//is mutable decoratedVariable can be modified in the const function} #pragma function Overload: The const function and the non-const function can form a function overload relationship};//main function int main (int argc, const char * argv[]) { Create Object Employee em ("Zhang San", 18); Em.show (); Em.setname ("Harry"); Here is the modified member variable em.show (); Em.setname ("Dfghj"); Em.getname (); #pragma what happens if I have this object that is a const type object? Can em2 call the Show method? Const Employee EM2 ("Reese", 21); Em2.show (); cannot be called. Why? Because the/* Const type of object indicates that all member variables in this object are not allowed to be modified but the Show method is not modified at the time of calling the Show method, but it can be modified. Then I am not relieved, you said you do not modify, but you can modify the EM2 call Show method, the em2 implicitly passed in, and then the show method inside can get the object by this-> to get the variable */#pragma how to let it call? Just make sure that you really don't change any variables in this function//how to guarantee? I modify this function to Const EM2.SHOW2 ();//const objects can only call member functions of the Const type EM.SHOW2 ();//Ordinary objects can also be called #pragma so there is no function that modifies the member variable in some functions or Plus a const good. Getter method can be added, setter method cannot add em2.getname (); Em2.setname ("Dfghj");//cannot call return 0;}
const objects and const member functions in C + +