Translator Note: This article is excerpted from the 16th chapter of "How-to-like" Computer scientist,learning with C + +, author Allen B. Downey). This book for the domestic "junior" C + + enthusiasts, is a rare introductory books. My version of this is Palm ebook.
Body:
I think the simplest way to explain pointers and references is to illustrate the evidence. First let's look at some expressions: x=1;
in an expression, when you use a variable, especially a letter or tag, to store the data. In the programming process, the variables in the above equation must be on the left side of the equals sign.
You may have noticed that the compiler does not allow you to write code like this:1=x;
If you do not know, you should now know, and understand it, this is the most critical. When you get compile run-time errors, such as: "Lvalue requied in ..." is because the left side of the equal sign is usually treated as a lvalue value and must be an address in memory.
Let's think about it. If you want to store the data, know where to store it before you store the data operation. The Lvalue value is a section of address in memory that holds your information or the data on the right side of the equal sign, as well as the rvalue value.
In C + +, you will often involve memory management in this or that way. Operation address, C + + has two kinds of mechanisms: pointers and References.
16.1 What is pointers and References
Pointers and references are special variables that store memory addresses as their values. Before you learn these, other relevant types of data types are:
Int,double and Char. Pointers and references store the addresses of the data you manipulate, with different data types that have been declared and assigned. These two mechanisms, pointers and References, have different syntax and different inertial use methods.
16.2 Statements Pointers and References
When you declare a pointer to an object or data type, you routinely use a method of declaring variables and data types, and only now, for a pointer to a declaration SomeType, you need to add an asterisk between the data type and its variables.
SOMETYPE* sometype;
int* x;
For declaring a reference, what you do is exactly the same as declaring a pointer, only this time you do not use the asterisk *, use-to replace.
SOMETYPE& sometype;
int& x;
As you may have learned, empty spaces are not considered in C + +, so the following pointer declarations are the same effect:
SOMETYPE* sometype;
SOMETYPE * sometype;
SOMETYPE *sometype;
The same is true of the following references statement:
SOMETYPE& sometype;
SOMETYPE & sometype;
SOMETYPE &sometype;