1. the const member function only tells the compiler that the class object is not modified, but cannot be blocked. Program The compiler may not be able to detect all possible modification actions, such as pointer modification.
2. For const member functions defined in vitro, the const modifier 1 class classname is required in definition and description.
2 {
3 public:
4 classname (){}
5 ~ Classname ();
6
7 void Foo ()
Const ;
8 char & operator [] (int I );
9 private:
10 //.
11}
12
13 void classname: Foo ()
Const
14 {
15 //
16}
17
18 char & classname: operator [] (int I)
19 {
20 //..
21}
22 int main ()
23 {
24 Const Classname OBJ ();
25 obj. Foo (); // OK
26 OBJ [2]; // error, coz [] not const
27}
28
3. The const object is a constant object. It can only call member functions declared as Const. . However, constructor and destructor are the only member functions that can be called by const objects but are not const member functions. Of course, a common object can also call a const member. 1 Class A
2 {
3 Public :
4 A ( Int X, Int Y): _ x (x), _ y (y ){}
5 // Int get () {return _ x ;}
6 Int Get () Const { Return _ Y ;}
7 Private :
8 Int _ X, _ y;
9 };
10
11 Int Main ()
12 {
13 A obj ( 2 , 3 );
14 Const A obj1 ( 2 , 3 );
15 Cout < OBJ. Get () < " " < Obj1. Get (); // 3 3
16
17 Return 0 ;
18 }
19
1 # Include < Iostream >
2 Using Namespace STD;
3
4 Class A
5 {
6 Public :
7 A ( Int X, Int Y): _ x (x), _ y (y ){}
8 Int Get (){ Return _ X ;}
9 // Int get () const {return _ y ;}
10 Private :
11 Int _ X, _ y;
12 };
13
14 Int Main ()
15 {
16 A obj ( 2 , 3 );
17 Const A obj1 ( 2 , 3 );
18 Cout < OBJ. Get () < " " < Obj1. Get ();
19 // Error. obj1 is a constant object and cannot call non-const methods.
20 Return 0 ;
21 }
4. Const member functions can be overloaded by non-const member functions of the same parameter table.1 # Include < Iostream >
2 Using Namespace STD;
3
4 Class A
5 {
6 Public :
7 A ( Int X, Int Y): _ x (x), _ y (y ){}
8 Int Get (){ Return _ X ;}
9 Int Get () Const { Return _ Y ;}
10 Private :
11 Int _ X, _ y;
12 };
13
14 Int Main ()
15 {
16 A obj ( 2 , 3 );
17 Const A obj1 ( 2 , 3 );
18 Cout < OBJ. Get () < " " < Obj1. Get ();
19 // 2 3
20 Return 0 ;
21 }
22
4. To allow modification of member variables of a class, even the data member of a const object, mutable is introduced.
Declaring a data member as mutable indicates that the member can always be updated, even in a const member function.