普通值、指针、引用作为函数参数时的理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/this_is_me_anyway/article/details/80192574

       很多时候,我们都会看到在教科书上写着各种值传递,引用传递,一看一大堆,有时候看的还容易迷糊,什么情况该怎么传总是区分不清,下边我们用一小版块并结合代码实例讲解下。

一、值传递

// 普通值传递
void test(int num)
{
	num = 5;
	cout << "in function " << __FUNCTION__ << " " << "num = " << num <<  endl;
}
int main(int argc, char* argv[])
{
	int num = 9;
	test(num);
	cout << "in function " << __FUNCTION__ << " " << "num = " << num << endl;

	getchar();
	return 0;
}
输出结果如下:

in function test num = 5

in function main num = 9

可见按值传递,在test函数内部,修改num的值,对实参num并无影响,即test函数接收到的实际上是外层num的一个拷贝。

// 指针按值传递
void testPt(int * p)
{
	p = new int;
	*p = 9;
	if (p)
	{
		printf("%d\n", *p);
		printf("in function %s p = %p\n", __FUNCTION__, p);
	}
}

int main(int argc, char* argv[])
{
	int *p = NULL;
	testPt(p);
	printf("in function %s p = %p\n", __FUNCTION__, p);
	getchar();
	return 0;
}

输出结果如下:

9
in function testPt p = 032C5978

in function main p = 00000000

在这里我们需要稍微注意下,指针作为一种特殊的值(相对于上一种情况的int值而言)进行传递,结合testPt理解,在testPt内部对该参数进行分配内存,从输出结果可以看到在函数内部的值已改变,但是在main函数体的p依然没有改变,而已这样也是值拷贝,不具备回传效果。

下边的涉及部分new空间没有释放,有些是演示的需要,实际开发中,可不能这样哦,哪里new了,对应就得释放掉。

二、指针的引用传递

实例:

void testptref(int* &pref)
{
	pref = new int();
	if (pref)
	{
		*pref = 9;
		printf("%d\n", *pref);
		printf("in function %s pref = %p\n", __FUNCTION__, pref);
	}
}

int main(int argc, char* argv[])
{
	int * pref = NULL;
	testptref(pref);
	printf("in function %s pref = %p\n", __FUNCTION__, pref);
	
	getchar();
	return 0;
}

输出结果如下:

9
in function testptref pref = 02674F08

in function main pref = 02674F08

可以看到,在testptref函数内外输出的结果一样了,说明内部的修改对传入的实参起作用了。对指针的引用作为参数传递,其实并没有拷贝,而是使用了同一个变量。

三、二级指针作为参数传递

二级指针一般形式为int**p; 我们通常认为,一个指针变量存储一个它所指向内容的地址。二级指针变量存储的是指向地址的地址,即存储了一级指针变量的地址。

实例:

void  test2pt(int **p)
{
	// 修改的是一级指针。
	*p = new int();
	if (*p)
	{
		**p = 9;
		printf("%d\n", **p);
		printf("in function %s p = %p\n", __FUNCTION__, *p);
	}
}

int main(int argc, char* argv[])
{
	int *p = NULL;
	test2pt(&p);
	printf("in function %s p = %p\n", __FUNCTION__, p);
	getchar();
	return 0;
}

输出结果如下:

9
in function test2pt p = 030A4F08

in function main p = 030A4F08

从结果可以看到,内外的指针值,即内部函数的修改对外部的该指针也起作用了。

猜你喜欢

转载自blog.csdn.net/this_is_me_anyway/article/details/80192574