Slide # 1

Slide # 1

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts Read More

Slide # 2

Slide # 2

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts Read More

Slide # 3

Slide # 3

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts Read More

Slide # 4

Slide # 4

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts Read More

Slide # 5

Slide # 5

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts Read More

Friday, November 12, 2010

C++ - Reference

Reference

Its biggest use is like function’s argument. First have to see how C++ sends the arguments to the function. One manner is by value. This method is coping. It makes copy of the argument and let it to go to the function. Second manner is by reference. Every method copy the argument’s address in parameter. With this manner it makes direct operation in the function of original variable which is like argument, but not to the copy.

Exist three manners for sending arguments to function: by value; by pointer and by reference.

With the first manner the copy is sending to the function. The second and third make the same matter, operate self argument, and not on the some its copy.









void swap(int *x, int *y){

                int t;

                t = *x;


                *x = *y;

                *y = t;

}





By invoke in the main program, this function look for addresses like entrance arguments.







swap(&i, &j);




A reference declares with operator & before the variable:







void f(int &i){


                i  = 10;

}



The argument modifies, without difference which was the variable’s value, after performing the previous function, the variable’s value which entered like argument is 10.








void swap(int &x, int &y){

                int t;

                t = x;


                x = y;

                y = t;

}




By invoke to this function the variables enter same like and sending by value, swap(i, j).


Reference can be backed from function. With this it has a lot of possibilities, more often it uses to preload at operator.

Exist some regulations for using reference:




- it can’t allocate the same reference to more arguments, it is possible just to one;


- it can’t to create a rank of references;



- it doesn’t exist null reference, it means when it is created immediately it marks to some variable.



 

0 comments:

Post a Comment