C++ references and pointers--pointers as formal parameters and return values; references as formal parameters and return values

C++ references and pointers

Classification of pointers

//普通指针
int a = 10;
int* p = &a;
//第一类指针:常量指针;指向的地址可改,指向的地址中的数据不可改
const int* p1 = &a;
//第二类指针:指针常量;指向的地址不可改,指向的地址中的数据可改
int* const p2 = &a;
//第三类指针:const int* const p;指向的地址和指向的地址中的数据都不可以改
const int* const p3 = &a;

The pointer saves an address. The definition of the pointer is to re-apply for a memory to save the pointed address in the memory. To access the data pointed to by the pointer p, you need to dereference *p

quote

A reference is to rename an alias to existing data.
The essence of a reference is a second-type pointer, which cannot be changed.
The difference between a reference and a pointer is that the pointer p stores the address, and the new identifier newName after the reference is the stored value.
When accessing data, the pointer uses *p, and the reference uses newName

test code

#include <iostream>

int* fun1(int *num)//返回值类型是止指针类型的数据,返回值保存的是一个指针()地址
{
    
    
	//指针的方式传输参数,形参num更改,那么对应的传进来的实参也会有相应的更改
	*num += 100;//指针需要解引用才能对指针指向的数据进行操作
	return num;//返回的是指针保存的地址,在函数体外部新建一个变量接收指针保存的地址
}

int& fun2(int& num)//返回值类型是引用的方式进行返回的,
{
    
    
	//引用本质是指针常量,但是,引用和指针的区别:指针还需要解引用才能读出指针指向的数据,但是引用不需要
	//num是对实参的一个别名,和实参一起共享在内存中的地址和数据,但是形参改变实参也会随着改变
	num += 200;//
	return num;//返回的是数值,引用的方式返回,在函数体外部给返回值起一个别名接收数据
}

int& fun3(int* num)//返回值是引用的方式,return的是一个数值
{
    
    
	*num += 500;//形参是一个指针,解引用后才是数据
	return *num;//对指针进行解引用后,将数值通过引用的方式返回,在函数体外部给数值起一个别名接收数据
}

int main()
{
    
    
	int num1 = 1;
	int num2 = 2;
	int  num3 = 3;
	int* p = fun1(&num1);//形参是指针,返回值是指针,
	int p1 = fun2(num2);//形参是引用,返回值是引用
	int p2 = fun3(&num3);//形参是指针,返回值是引用

	std::cout << "num1:" << num1 << std::endl;
	std::cout << "num2:" << num2 << std::endl;
	std::cout << "num3:" << num3 << std::endl;

	std::cout << "fun1返回值是指针:" << *p << std::endl;
	std::cout << "fun2返回值是引用:" << p1 << std::endl;
	std::cout << "sun3返回值是引用:" << p2 << std::endl;

	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_50727642/article/details/123251474
Recommended