C++_CH12_引用
1.1 引用不是一个变量
#include<iostream>
int main()
{
int a = 8;
int& ref = a;
ref = 2;
std::cout<<a<<std::endl;
std::cin.get();
}
output:
2
ref并不是一个变量。这里只是一个语法。这样的语法使得
int& ref 和 a等价。但是ref并不是创建的一个变量。
如果对ref修改对应的变量是不成立的:
#include<iostream>
int main()
{
int a = 8;
int& ref = a;
int b = 1;
ref = 2;
ref = b;//b的值给了a
int& ref = b; //对ref重复定义。错误,因为ref已经被定义为了a,就不能是别的。
ref = 9;
std::cout<<a<<std::endl;
std::cout<<a<<std::endl;
std::cin.get();
}
output:
main.cpp:10:7: error: redefinition of 'ref'
int& ref = b;
^
main.cpp:6:7: note: previous definition is here
int& ref = a;
^
1 error generated.
我们删除int& ref = b;
#include<iostream>
int main()
{
int a = 8;
int& ref = a;
int b = 1;
ref = 2;
ref = b;//b的值给了a
std::cout<<a<<std::endl;
std::cout<<a<<std::endl;
std::cin.get();
}
output:
1
1
1.2 分别利用指针、引用传参
普通传参
#include<iostream>
void LinearAdd(int a)
{
a++;
}
int main()
{
int b = 0;
LinearAdd(b);
std::cout<<b<<std::endl;
std::cin.get();
}
output:
0
你会发现,b的值并没有增加,这是因为b在进行传参的时候,是将自己的值复制了一份给了LinearAdd,在该函数体内,对这个复制的值加了1,但这只是改变了复制的值,并不会影响到b的值,所以b的值还是老样子。我们真正应该传的参是b的地址,这样才会真正改变存放b的内存单元内的数据。
指针传参
我们修改一下代码:
#include<iostream>
void LinearAdd(int* a)//形参是指针变量
{
a++;
}
int main()
{
int b = 0;
LinearAdd(&b); //因为形参是int* a,所以实参应该是取b的地址。即int* a = &b
std::cout<<b<<std::endl;
std::cin.get();
}
output:
0
为什么还是0?
回到LinearAdd函数体内,我们看到
a++
此时的a是什么?是b的地址,那么a++只是对b的地址++,我们要的是对b的值++,所以还需要解引用
#include<iostream>
void LinearAdd(int* a)//形参是指针变量
{
*a++;
}
int main()
{
int b = 0;
LinearAdd(&b); //因为形参是int* a,所以实参应该是取b的地址。即int* a = &b
std::cout<<b<<std::endl;
std::cin.get();
}
output
0
还是0,为啥?
*a++
是对地址++后再解引用,我们要的是先解引用再++
#include<iostream>
void LinearAdd(int* a)//形参是指针变量
{
(*a)++;
}
int main()
{
int b = 0;
LinearAdd(&b); //因为形参是int* a,所以实参应该是取b的地址。即int* a = &b
std::cout<<b<<std::endl;
std::cin.get();
}
output
1
成功
引用传参
实际上使用指针的代码还是不够简洁。我们可以利用引用传参。
#include<iostream>
void LinearAdd(int& a)//形参是指针变量
{
a++;
}
int main()
{
int b = 0;
LinearAdd(b); //因为形参是int* a,所以实参应该是取b的地址。即int* a = &b
std::cout<<b<<std::endl;
std::cin.get();
}
引用传参相当于:
int& a = b
因此实参只需要是b就行,函数体内也不需要解引用。这个语法在数据结构中非常有用。