C++_CH12_引用

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就行,函数体内也不需要解引用。这个语法在数据结构中非常有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值