Source: http://blog.csdn.net/qianchenglenger/article/details/16949689
1.int I-value, int & I-pass reference
int I does not return parameters, and int &i can be returned with parameters, such as
[CPP]View PlainCopy
- #include <iostream>
- void test1 (int i)
- {
- i = 7;
- }
- void Test2 (int &i) //To limit parameter changes, you can add a const limit
- {
- i = 7;
- }
- int main ()
- {
- int t1 = 10;
- Test1 (t1);
- Std::cout << T1 << Std::endl; //output is ten
- int t2 = 10;
- Test2 (T2);
- Std::cout << T2 << Std::endl; //output is 7
- return 0;
- }
2. int I can assign constants, and int & I cannot
[CPP]View PlainCopy
- #include <iostream>
- void test1 (int i)
- {
- i = 7;
- }
- void Test2 (int &i)
- {
- i = 7;
- }
- int main ()
- {
- int i = 10; //Legal
- int &i1 = 10; //Compilation error
- Test1 (10); //Legal
- Test2 (10); //Compilation error
- return 0;
- }
3. int &i is equivalent to an alias, and int i is just a copy
[CPP]View PlainCopy
- #include <iostream>
- int main ()
- {
- int t1 = 10;
- int t2 = 10;
- int i1 = t1; //Copy
- int &i2 = t2; //Aliases
- I1 = 7;
- I2 = 7;
- Std::cout << T1 << Std::endl; //Output ten
- Std::cout << T2 << Std::endl; //Output 7
- return 0;
- }
Finally, let's take a look at another example
[CPP]View PlainCopy
- #include <iostream>
- Class a{
- Public
- A (int a, int b): I1 (a), i2 (b) {};
- Public
- int i1;
- int &i2;
- };
- int main ()
- {
- A (45,60);
- Std::cout << a.i1 << "<< a.i2 << Std::endl;
- return 0;
- }
After running on the computer, you will find that the first number is normal, and the second number is obviously an undefined value, for example, I get the result after running
45 1400458944
This is because when we construct an object, we call the constructor, and the argument to the constructor of a is passed as a value, so when called, it is equivalent to having a
[CPP]View PlainCopy
- int B = 60
I2 (b) is the equivalent of
[CPP]View PlainCopy
- int &i2 = b;
When the constructor call is complete, the scope of B is ended, B is destroyed, and i2 points to a place that has been destroyed, an undefined run result appears.
We're going to post a procedure that corresponds to the previous paragraph, but this time we'll get 45 60 results.
[CPP]View PlainCopy
- #include <iostream>
- Class a{
- Public
- A (int a, int &b): I1 (a), i2 (b) {};
- Public
- int i1;
- int &i2;
- };
- int main ()
- {
- int t = 60;
- A (45,t);
- Std::cout << a.i1 << "<< a.i2 << Std::endl;
- return 0;
- }
&i Considerations for int i and int in C + +