I. the const class member functions have the following notes:
1. in a common non-const member function, the this type is a const pointer to the class type, while in the const member function, this is a const pointer to a const class object. For this reason:
(1) Return Value Function Name (parameter list) const {...} This format can only be used in member functions of the class. Non-member functions can only use this format: void F1 (const STD: string & S );
(2) If you want to return the reference (* This) of this class object, add const before the return value declaration (the pointer to the const object or the reference must be of the const type ).
2. You can perform heavy loads based on whether the member function is const. Note the following:
(1) The const label in the const member function must be specified in the function declaration and definition;
(2) A const object can only use the const member function. A non-const object can use any member.
3. Const cannot be declared as Const.
[CPP]View plaincopy
- # Include <iostream>
- Using namespace STD;
- Class
- {
- Public: // explicit a (INT); // error: you cannot convert parameter 1 from "int" to "const a". The object cannot automatically convert const to non-Const, however, it is okay to convert non-const to const. Therefore, the essence of the problem is that parameter 1 cannot be converted from "int" to "const ", because explicit makes the implicit conversion generated by the constructor impossible.
- A (INT );
- // A () const; --> error: "const" "This" pointer is invalid for constructors/destructor
- Int getnum () const; // const must have
- PRIVATE:
- Int num;
- };
- A: A (int)
- {
- Num =;
- }
- Int A: getnum () const // note that there is a reason for this design, because the const-based function can be overloaded, and the const is part of the signature, if no const is written here, the compiler will prompt that the overloaded member function cannot be found.
- {
- Return num;
- }
- Int test (const)
- {
- Return A. getnum (); // The internal function of the const object must be const, whether or not the member variable is modified,
- }
- Int main ()
- {
- Cout <Test (2 );
- Int I;
- Cin> I;
- Return 0;
- }
2. There are several important points for const data members:
1. Const static int can initialize static data members in the class definition body;
2. You can declare a data member as mutable to change the data member of this class const object;
3. the only opportunity for initializing a const data member is that the initialization list of the const function is incorrect either in the class definition body or in the definition body of the const function.