References and some of the const

Source: Internet
Author: User

One, reference: a reference to a variable is equivalent to this variable, which is an alias of the variable.

#include <iostream>intMain () {intA=2, b=1; int&c=a;//(1) Be sure to initialize when defining referencesC=3; Std::cout<<a<<Std::endl; C=b;//Instead of C referencing B, the value of C (which is actually the value of a variable) becomes the value of the B variable, and the reference to C cannot be changed//(2) Once the reference is initialized, no other variables are referenced. std::cout<<a<<Std::endl; b=2; Std::cout<<a<<Std::endl; //int &i=2; //Error//int& j=a*4;    /**invalid Initialization of non-const reference of type ' int& ' from an rvalue of type ' int ' * (3) References can only reference variables, not Can reference constants and expressions*/    return 0;}

Examples of references:

#include <iostream>/** The value of the pass is actually a copy of the argument, so the argument does not change, but the copy of the argument is changed.*/voidSWAP1 (intAintb) {    inttemp=A; A=b; b=temp;}/** The value of the argument can be changed by an indirect reference to the pointer (PS: The pointer parameter is actually a value, and a pointer copy points to the argument, but the value of the argument can also be changed by this pointer)*/  voidSWAP2 (intAint*b) {    inttemp=*A; *a=*b; *b=temp;}/** By reference type we can actually manipulate the value of the argument, because the reference is an alias of the variable*/  voidSWAP3 (int& A,int&b) {    inttemp=A; A=b; b=temp;}intMain () {intA=2, b=1;    Swap1 (A, b); Std::cout<<"A:"<<a<<Std::endl; Std::cout<<"B:"<<b<<Std::endl; SWAP2 (&a,&b); Std::cout<<"A:"<<a<<Std::endl; Std::cout<<"B:"<<b<<Std::endl;    SWAP3 (A, b); //call is not referencedstd::cout<<"A:"<<a<<Std::endl; Std::cout<<"B:"<<b<<Std::endl; return 0;}

function return Reference type

#include <iostream>int n=3int& revalue () {    return  N;} int Main () {    revalue ()=+;    Std::cout<<n<<std::endl;     return 0 ;}

Two, const object: If you do not want the value of an object to be modified, you can add the Const keyword before the object is defined.

#include <iostream>using namespacestd;classa{ Public: A (): A (0){}    voidSetnum () {a++;//the existence or absence of this statement is not compiled by the program    }Private:    intA;};intMain () {ConstA;    A.setnum (); return 0;}//[Error] passing ' const A ' as ' this ' argument of ' void a::setnum () ' Discards qualifiers [-fpermissive]

Conclusion: The non-static member function uses this to manipulate the value of the const a type object A. This is a non-conforming definition (as this allows the object to be modified). So a const object cannot call a non-static member function, although it does nothing.

#include <iostream>using namespacestd;classa{ Public: A () {}Static voidSetnum () {a++; }Private:    Static intA;};intA::a=0;intMain () {ConstA;    A.setnum (); return 0;}

Conclusion: A const object can call a static member function, although he modifies some static member variables.

three, const member functions (constant member function): The object whose effect should not be modified during the execution of a constant member function.

#include <iostream>using namespacestd;classa{ Public: A (): A (0){}    voidRead ()Const    {        //a++; //The const member function does not modify non-static member variablesb++; }Private:    intA; Static intb;};inta::b=0;intMain () {a A;    A.read (); return 0;}

Conclusion 1, a constant member function cannot modify the value of a member variable. (except for static member variables);

#include <iostream>using namespacestd;classa{ Public: A (): A (0){}    Static intGetnum () {returnb;} voidSetnum () {a=1;} voidRead ()Const    {        //Setnum (); //[Error] passing ' const A ' as ' this ' argument of ' void a::setnum () ' Discards qualifiers [-fpermissive]Getnum (); }Private:    intA; Static intb;};inta::b=0;intMain () {a A; A.read ();}

Conclusion 2, a constant member function cannot call a homogeneous member function (except static member functions);

So we remember that the const object above cannot call the normal member function, but by learning the const member function we know that the Const object can call the const member function.

#include <iostream>using namespacestd;classa{ Public: A (): A (0){}    voidSetnum ()Const{}Private:    intA;};intMain () {ConstA;    A.setnum (); return 0;}

Const member function overloading : Two functions if the name parameters are the same, but one is const, one is not, which counts as overloading.

#include <iostream>using namespacestd;classa{ Public: A (): A (0){}    intRead ()Const    {        returnA; }    intRead () {a++; returnA; }Private:    intA;};intMain () {ConstA A1;//calling the const member functionA A2;//calling non-const member functionscout<<"A1 Read return:"<<a1.read () <<Endl; cout<<"A2 Read return:"<<a2.read () <<Endl; return 0;}

Four, constant reference : The reference is preceded by the Const keyword, which becomes a constant reference and cannot be modified by a reference to its referenced value.
Object as a parameter is, a function call is an object that invokes a copy constructor and is inefficient. Use pointers as arguments, code is not good to see--"pass the reference
A direct reference is sometimes flawed: when we don't want the object to change, it's possible that this function modifies the object at this point. That's not what we want.
So we can use the object's constant reference as a parameter: it improves efficiency and does not modify the object.

class a{...}; void Compare (const a& A) {...}

Five, finally mention the function call method.
Look at the differences between the following two different invocations.

A; A* p = &a;a.getnum ();p->getnum ();

C + + supports three types of member functions: Static,nonstatic,virtual. There are different calls to the three member functions.
supplement: the static member function cannot do two points: 1, cannot manipulate nonstatic members, 2, cannot be declared as Const.
1,static members do not rely on objects, nonstatic dependent objects, so static member functions cannot invoke nonstatic members. However, the nonstatic member function can call a static member,
2, not a member function that is modified at the same time as static and Const. Because the normal member function implies a pointer to the class object, the same const-decorated member function implicitly has a const this pointer to ensure that the function does not modify the class object.
But the static member function does not accept the this pointer, because it does not exist because it violates the two.

nonstatic member function

 class   a{ public  : A (): Val ( 0   int  Getnum () {return   Val;}  private  :  int          Val; }; int      main () {a A;    A  * p = &A;    A.getnum ();    P ->getnum ();  return  0  ;}  

The difference between the above two call member functions:
First of all, the member function has already made some conversions: an extra parameter (this pointer) is placed into the parameter list, and then the operation of the non-static data member is manipulated by this pointer.

int Const This)  // if the const member function is a const * Const This {    returnthis, Val;}

So the call to A.getnum () above becomes getnum (&a); the call to P->getnum () becomes Getnum (p);

The this pointer above can not change the point but can change the point of the object, while the const this pointer can neither change the point, nor change the object to point to-"so the const member function can manipulate the const object.

virtual function:
If the above function Getnum () is a virtual function call is changed again: (due to the virtual function table)
P->getnum () will be internally converted to (*p->vptr[1]) (p)//vptr is a pointer to the virtual function table, then the address of the virtual function is obtained by the index, and then the virtual function is called. The p in the function parameter list indicates the this pointer
A.getnum () will be converted internally to (*a.vptr[1]) (&a)

Static member functions:
For the static member function, A.getnum () and P->getnum () will be converted to general nonmember function calls.

References and some of the const

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.