C + + General const usage Notes

Source: Internet
Author: User

C + + General const usage Notes

1. Const-Decorated class member variables

Program:

#include <iostream>usingnamespace  std; class a{    public:        A (int  size): size (size) {};     Private :         Const int SIZE;}; int Main () {    A A (+);}

Description
(1) Declaring a variable to be a const type in a class, but not initialized;

(2) The initialization of a member variable of a Const constant class must be initialized in the constructor initialization list , not in the constructor function body.

(3) If it is defined as a member of Class C, because the object cannot be created in the Class C definition, you can take the following actions:

         Use the pointer, and then in the constructor of Class C, create the object in heap space with new, and then initialize the members of the const number of days.

  

 When the const variable belongs to a specific object, how is it constant in the whole class ?

  The answer is to use enumerations

#include <iostream>usingnamespace  std; class a{    private:        enum[+]    ;  Public :         int array[size];}; int Main () {    a A;}

Problem Description:

(1) enumeration constants do not occupy the object's storage space and are evaluated at compile time

(2) However, it implies that the data object type is shaping and cannot represent other types .

2. conditions that must be initialized in the initialization list of the constructor

  (1) A const constant of a class;

(2) A reference type member of a class;

#include <iostream>using namespacestd;classa{ Public: A (int & v): I (v), P (v), J (v) {}voidPrint_val () {cout <<"Hello:"<< I <<"  "<< J <<Endl;} Private:        Const inti; intp; int& J;};intMainintARGC,Char**argv) {    intPP = $;    A b (PP); B.print_val ();}

the reason

① Const Objects or references can only be initialized but cannot be assigned a value .

The function body of the ② constructor can only be assigned instead of initialized , so the only chance to initialize a const object or reference is in the initialization list before the body of the constructor function.

③ understands two concepts:

  From Scratch called initialization , initialization (call copy constructor ) creates a new object ;

  Assignment (called Assignment operator ) does not create a new object , but instead assigns a value to an existing object.

(3) class type member without default constructor

#include <iostream>using namespacestd;class Base{ Public: Base (inta): Val (a) {}Private:        intVal;};class A{ Public: A (intv): P (v), B (v) {} voidPrint_val () {cout <<"Hello:"<< P <<Endl;} Private:        intp; Base b;};intMainintARGC,Char**argv) {    intPP = $;    A b (PP); B.print_val ();}

The same reason is that each member of the class member is initialized when the object is created .

(4) If the class has an inheritance relationship, the derived class must call the constructor of the base class in its initialization list;

#include <iostream>using namespacestd;classbase{ Public: Base ( int a) : Val (a) {}Private:        intVal;};classA:public Base{ Public: A (intv): P (v), Base (v) {}voidPrint_val () {cout <<"Hello:"<< P <<Endl;} Private:        intp;};intMainintARGC,Char**argv) {    intPP = $;    A b (PP); B.print_val ();}

3. Const member functions

(1) Any function that does not modify a data member should be declared as a const type.

If the const member function is written,① inadvertently modifies the data member, ② or calls other non-const member functions , the compiler will indicate the error. Should form a good habit.

 Note: In const-decorated class member data, the const declaration is generally behind the function declaration;

#include <iostream>using namespacestd;classstack{ Public:        voidPush (intitem); intPop (void); intGetCount (void)Const; //const Rear-facing Private:        intM_num; intm_data[ -];};intStack::getcount (void)Const{    ++m_num;//compilation error, attempting to modify data memberPop ();//compile error, attempt to invoke non-const function    returnM_num;}

(2) in the same class, you can only define two function names, parameters, and return values exactly the same two member functions by whether or not const, depending on whether the class object is a const object called separately.

Program:

#include <iostream>using namespacestd;classa{ Public: A (intv): Val (v) {}voidPrint_val () {cout <<"Not const:"<< Val <<Endl;} voidPrint_val ()Const{cout <<"Const Print_val:"<< Val <<Endl;} Private:        intVal;};intMainintARGC,Char**argv) { A B (  $);    B.print_val (); Const A A (); A.print_val ();}

Output:

  

Summarize:

The same function name, parameter, and return value can only be defined as two member functions of a class by whether it is Const.

When called, a const object calls a const member function, and a non-const object calls a non-const member function.

4. Some issues with the const

(1) The value of the member variable cannot be changed in the Const function, then is there any way to change it?

The answer is yes, declare the member variable as the mutable type. See the program

#include <iostream>using namespacestd;classa{ Public: A (intv): Val (v) {}voidPrint_val () {cout <<"Not const:"<< Val <<Endl;} voidPrint_val ()Const{val++; cout <<"Const Print_val:"<< Val <<Endl;} Private: mutable intVal;};intMainintARGC,Char**argv) {A B ( $);    B.print_val (); ConstA A ( A); A.print_val ();}

Output:

  

Description

  The Chinese meaning of mutalbe is "mutable, variable", and constant (both const in C + +) are antonyms.

  In C + +, mutable is also set to break the limits of Const. Variables that are modified by mutable will always be in a mutable state, even in a const function.

We know that if the member function of a class does not change the state of the object, then this member function is generally declared as Const. However, there are times when we need to modify some data members that are unrelated to the class state in the Const function, then this data member should be mutalbe.

(2) can a non-const object call a const function when there is only a const function in the class?

  The answer is yes, the scope has not been enlarged.

  However: when there is only a const function, non-const objects cannot investigate that const function (otherwise, the data variables of the class will change).

(3) Can a const function temporarily invoke the non-const function when there are two functions in the class that are different only for const?    

The answer is yes. Using const_cast will transform the const nature of the expression

#include <iostream>using namespacestd;classa{ Public: A (intv): Val (v) {}voidPrint_val () {cout <<"Not const:"<< Val <<Endl;} void ConstPrint_val ()Const{cout <<"Const Print_val:"<< Val <<Endl;} Private:        intVal;};intMainintARGC,Char**argv) {A B ( $);  B.print_val (); Non-constConst A *a=NewA $); const_cast <A*>(a)Print_val (); () call the non-const overloaded function a-Print_val (); Call const from in function}

Output:

  

Note that;const_cast<a*> (A) is only valid for local conversions and must be handled using a pointer to the class.

  Simply use class to transform not, directly with the object of the class does not.

Const A (a); const_cast<A> a.print_val ();

Compilation does not pass, error

(4) Return type is const What's going on?

  The const return type is only useful if the modifier pointer or reference is available. The const return type cannot be overloaded.

Reference URL:

Http://www.cnblogs.com/kaituorensheng/p/3244910.html

C + + General const usage Notes

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.