C++基础(七)引用 指向指针的引用

用途    给变量起别名

语法    数据类型  &别名  =  原名

注意    新建引用必须初始化    引用不可更改指向  

本质    本质上就是一个指针常量     int * const p = &a;

#include <iostream>
using namespace std;

int main()
{
	int a = 10;
	int& b = a;
	cout << a << "    " << b << endl;
	return  0;
}

引用做函数形参的小例子

#include <iostream>
using namespace std;

void swap(int a,int b)
{
	int temp = a;
	a = b;
	b = temp;
}
//指针的方式交换
void swap01(int* a, int* b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}
//引用的方式交换
void swap02(int& a, int& b)
{
	int temp = a;
	a = b;
	b = temp;
}
int main()
{
	int a = 10;
	int b = 20;

	swap(a, b);
	cout << "a:" << a << "b:" << b << endl;
	swap01(&a, &b);
	cout << "a:" << a << "b:" << b << endl;
	swap02(a, b);
	cout << "a:" << a << "b:" << b << endl;
	return  0;
}

注意    不可以利用函数直接返回局部变量的引用

            可以利用函数返回常量的引用

            返回值为引用的函数可以作为被赋值的一方使用

#include <iostream>
using namespace std;

int& run() 
{
	static int a = 10;
	return a;
}

int main()
{
	int& p = run();
	cout << p << endl;
	cout << p << endl;
	run() = 100;
	cout << p << endl;
	cout << p << endl;
	return 0;
}

使用const关键字修饰形参防止误操作

void run2(const int& a)
{

}

指向指针的引用

函数形参为数组

#include <stdlib.h>
#include <string.h>

#pragma warning(disable:4996)
//二级指针接受一级指针
void writeStr(char ** str) {
    *str = (char *)calloc(1,23);
    strcpy(*str,"hello word");
    return;
}
//引用的写法
void writeStr2(char* &str) {
    str = (char*)calloc(1, 23);
    strcpy(str, "hello word 1");
    return;
}

void test01() {
    char* godv = NULL;
    writeStr2(godv);
    cout << godv << endl;
    free(godv);
}

int main()
{
    test01();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值