In our previous articles, we have already mentioned that, that parameters can be passed to the function by value or the pointer. It worked when writing programs in C. In C ++, it is possible to pass parameters to the link function. Consider the example of this lesson, you will notice, links that use more convenient than pointers.
Reference – is an alternative name of the variable (her nickname, in other words). When the function takes a parameter by reference, the name of the parameter becomes the nickname variable, that we pass to the function. This data transfer method allows the function to work with variables, which are transmitted to it, rather than copies of these variables.
Defining a function, to point, that the parameter is a reference, it is necessary to add the name of an ampersand &.
Collect the following example, and everything should be clear:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <iostream> using namespace std; void showVariables(int varInt, double varDbl); void change(int varInt, double varDbl); // передача по значению void changeRef(int& varInt, double& varDbl); // передача по ссылке void changePtr(int* varInt, double* varDbl); // передача по указателю int main() { setlocale(LC_ALL, "rus"); int varInteger = 0; double varDouble = 0.0; cout << "Передаем параметры по значению!" << endl; change(varInteger, varDouble); showVariables(varInteger, varDouble); cout << "Передаем параметры по ссылке!" << endl; changeRef(varInteger, varDouble); // передаем, как обычную переменную showVariables(varInteger, varDouble); cout << "Передаем параметры по указателю!" << endl; changePtr(&varInteger, &varDouble); // используем амперсанд, чтобы передать адрес showVariables(varInteger, varDouble); return 0; } void showVariables(int varInt, double varDbl) { cout << "Значения переменных после изменений:\n"; cout << "Первая переменная (int) = " << varInt << endl; cout << "Вторая переменная (double) = " << varDbl << endl; cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"; } //================================================================ void change(int varInt, double varDbl) { varInt = 100; varDbl = 111.11;; } //================================================================ void changeRef(int& varInt, double& varDbl) { varInt = 200; // обращаемся, как к обычной переменной varDbl = 222.22; } //================================================================ void changePtr(int* varInt, double* varDbl) { *varInt = 300; // применяем разыменование *varDbl = 333.33; } |
Let's start with the functionchange(). Calling it in string 17 source, we pass it in the variables by value. Function safely create copies of these variables, writes the data in them and, completing his “hard” work, destroy those copies. As a result, any changes to the transferred variables will not happen.
Now look at the function definition changeRef(), in which the parameters are passed by reference – strings 45 – 49. As mentioned above, We used & , to tell the compiler that, that accepts parameters – It references. Inside the function we refer to references, as ordinary variables. That is, we do not need to apply the dereference operation, if you need to change the value of a variable:
And calling this function from the main (string 21), we do not need, transmission variables, apply the operation of taking the address (same & , but with a different connotation), as necessary to make the transfer by the pointer. The result of the work function see, display the values of variables on the screen. The values of variables successfully changed.
Finally, – transmission pointer. Directly to the definition of changePtr() – strings 51 – 55. There is something, which we did not use at the reference transmission – dereference pointers to change values of variables:
Since the function is to take the pointer variables, and the pointer holds the address, when calling (string 25) pass the addresses of variables in it:
The result of the program work:
I do not really want to burden you any more information about references. They are most often used is to pass parameters to a function. In the role of the parameters can act variables, arrays (it is familiar to us). But what is more important – the reference to the function objects are passed structures and classes. The time will come and we'll talk about it.
Only, It is regarding syntax, if you need to declare a reference to the program, it must be immediately initialize (to show how variable it is created). For example:
So the program we can use the reference name for further access to your data, that stores aaa. This example if someone is up to you to write the code and gave the name of the variable aaa. This programmer knows, it stores the number of boxes. And you, for your convenience, gave this variable an nickname amountOfBoxesand use this new name, appending some new code in a program.
I propose to see the video of the function parameters, including where and talked about references.
Reference – is an alternative name of the variable, IMHO longer here to explain nothing. variable one, name a few. By any name of a variable, you can somehow work. In the case with reference to the same function arguments, just an alternative name of the variable will be visible inside the function.
Well, a couple of examples, I would add.
unnecessarily. pointer – it is also variable (simply stores the address of an object), then the function can pass a reference to a pointer such as
void foo(int &*arr);
something like that.
And another example, есть 2 functions:
void foo(int * a);
void bar(int &a);
The first takes an object reference, second- pointer.
Somewhere in the program (for example in the main function is the object:
int var = 123;
If you need to pass it in the first function – we have to get the address of an object:
foo(&var);
secondarily – You can simply pass, while inside the function will use the alternative name of the object
bar(var);
If we need to define a pointer to an object – it must also be initialized address:
int * p = &var;
Inside the first function with the object of work as usual (because we just have an alternative name):
void foo(int &a) { a = 456; }
In the second function, we have a pointer, therefore forced to dereference it to access the object:
void bar(int * a) { *a = 789; }
// if a – pointer,
// then (*a) – an object,
// and (&(*a)) – Address Object brackets can be removed, set for clarity (they reflect the priorities).
The names are confused.
“And another example, есть 2 functions:
void foo(int * a);
void bar(int &a);
The first takes an object reference, second- pointer.”
On the contrary!
references – quite unpleasant for beginners concept in C ++ (although it is natural even for beginners in Java or Python).
For beginners can say so (although it is not quite tocho):
– variable reference – it is exactly the same, as a pointer to it, but this link, Unlike pointer, you can not use address arithmetic (+, -, ++, –).
It is inaccurate in the sense of, but immediately lets you use references in your code without errors.
Oleg, great that you pay attention to our articles and make important notes to the presentation of the material. Thank you and from the administrator of the site and, I think, from visitors )
Neither a beginner does not understand you. Your explanation does not understand, The following articles are yours and it is very difficult to understand, impossible. But this article is very easy to perceive. No more articles like pointers to functions
What means “no one”? Not only understand the most stupid ;-) … others anything, yes understand.
Programming – it generally is not simple engineering discipline, and to explain it “on finger” impossible harmfully same, how, for example, mathematical analysis and descriptive geometry.
And will be able to learn programming only, who will be long and hard practice and independently write code.
P.S. And by learning to explain the level of “two by two, Babes, sometimes turns four, if you do not mind” – No one learned nothing, there is only an illusion that “I, too, something studied there”.