Many application methods in C ++ are the same as those in C. What are the differences between the C language version and the C language version? First, let's interpret this question from the basic concepts referenced by C ++, hoping to help you easily grasp the characteristics of this language.
- How to use C ++ to call the C-Linked Library
- Summary of C ++ typedef usage
- Basic concepts of C ++ storage areas
- Common usage of C ++ templates
- C ++ global Function Application Guide
I. Concept of C ++ reference
Reference introduces a synonym for an object. The expression of the definition reference is similar to the definition pointer, but it is replaced *.
Example: Point pt1 (10, 10 );
Point & pt2 = pt1; defines a reference where pt2 is pt1. With this definition, pt1 and pt2 indicate the same object.
Note that C ++ references do not generate copies of objects, but only synonyms of objects. Therefore, after the current statement is executed:
Pt1.offset2, 2 );
Pt1 and pt2 both have 12, 12) values.
The C ++ reference must be initialized immediately at definition, because it must be a synonym for something. You Cannot initialize a reference before defining it. For example, the following statement is invalid:
- Point &pt3;
- pt3=pt1;
So what is the purpose of referencing a synonym for something?
The following describes the two main uses of C ++ reference: as a function parameter and return the left value from the function.
Ii. Reference parameters
Passing variable parameters
In traditional c, parameters are passed through values when a function is called, which means that the function parameters do not have the ability to return values.
Therefore, in traditional c, if function parameters are required to have the ability to return values, they are usually implemented through pointers. For example
The c program for the exchange of two integer values is as follows:
- void swapint(int *a,int *b)
- {
- int temp;
- temp=*a;
- *a=*b;
- *b=temp;
- }
After the C ++ reference mechanism is used, the C ++ version of the above program is:
- void swapint(int &a,int &b)
- {
- int temp;
- temp=a;
- a=b;
- b=temp;
- }
The C ++ method that calls this function is swapintx, y). C ++ automatically transmits the address of x and y to the swapint function as a parameter.