C ++ references and constants

constant:

There are many types of data (e.g., int, float, bool, etc.) in C ++. These data types can be declared in turn define the variables and constants in two different specific data. They are two classifications of the standard is not the same, are two angles can be superimposed classification For chestnut: int Description This is an integer variable x illustrate the variable number (unknown in mathematics), is a superposition of the two integer unknowns (there is an opaque box at how many balls, this number is unknown, but it must be an integer, there is no half ball).

For constant and variable, which is defined in the C ++ (vs) is different. We declare a variable just write int x, float y (x, y in mathematics also said unknown) can be. Then assignment of x and y, x = 10, y = 1.000. We declare variables are in general, the value of the variable in the program can be changed, because it is a variable thing.

The statement is a constant need const keyword or #define. Once the constant declaration can not be changed, such as PI is 3.14, it can not add or subtract, multiply and divide operations (which are mathematically consistent, pi is 3.14 can not be changed, the introduction of this data to the programming language is a constant), so, for D ++ operation is not permitted, in violation of logic (you can not modify it to pi in life)

#define and const difference:

FIG #define defined by the upper data types not only define a constant, not the corresponding inspection during operation, an error may occur. Const and back with the data type, in essence, is a float data, the space occupied by the data segment.

The most important point: #define just a data replacement, replace the data when it is needed

#define N 2+3 //我们预想的N值是5,我们这样使用N
double a = N/2; //我们预想的a的值是2.5,可实际上a的值是3.5

而造成这个问题的原因就是在N/2时,对N进行了一个替换展开,称为2+3,所以最后运算结果为2+3/2=3.5

引用:

It is a reference variable (target) of an alias, the operation of the variable references and direct operating exactly the same. The so-called people's understanding is simply an alias name with the same nickname.

 

  Disclaimer method references: type identifier reference name = & target variable name;

 

  int a=10;

   int & ra = a; // define references ra, which is a variable reference, i.e. aliases . Note: When you declare a reference, must be initialized.

 





Guess you like

Origin www.cnblogs.com/fqyf/p/11820160.html