c++中的引用(&)以及函数

 c++中的引用

int* func3() {
	//new返回的是该数据类型的指针
	int* a = new int(10);
	return a;
}

void test02() {
	int* arr = new int[10];
	for (int i = 0; i < 10; i++) {
		arr[i] = i + 100;
	}
	for (int i = 0; i < 10; i++) {
		cout << arr[i] << endl;
	}
	delete[] arr;
}


//引用作函数的返回值 


//1.不要返回局部变量的引用
//int& test03() {
//	int a = 10;
//	return a;
//}
//2.函数的调用可以作为左值
int& test04() {
	static int a = 10;
	return a;
}
//c++中一旦发现是引用,就转换为 int* const ref=&a;
void func4(int& ref) {
	ref = 100;//ref是引用,转换为*ref=100
}

int func5(int a, int b = 10, int c = 20) {
	return a + b + c;
}

 函数


//1.如果某个位置参数有默认值,那么从这个位置往后,从左向右必须要有默认值
//2.如果函数声明有默认值,函数实现的时候就不能有默认参数


int func6(int a = 10, int b = 20);
int func6(int a, int b) {
	return a + b;
}






void Print(const int& val) {
	//val = 666;
	cout << "val= " << val << endl;
}

void func7(int) {
	cout << "this if func";
}


int main() {
	/*int l_a = 10;
	cout << "字符串常量的地址 " << & "hello" << endl;
	cout << "全局变量的地址 " <<  & g_a << endl;
	cout << "局部变量的地址 " << &l_a << endl;*/
	//int* p = func2();
	//cout << *p << endl;
	//test02();

	/*int* p = func3();
	cout << *p << endl;
	delete p;
	cout << *p << endl;*/


	/*double a = 1.209;
	cout << a << endl;*/

	&(引用一旦初始化后就不能发生更改)
	//int a = 10;
	//int& b = a;
	//int c = 20;
	//b = c;

	//cout << "a= " << a << endl;
	//cout << "b= " << b << endl;
	//cout << "c= " << c << endl;

	/*int& ref = test03();
	cout << "ref= " << ref << endl;*/

	/*int& ref = test04();
	cout << "ref= " << ref << endl;
	cout << "ref= " << ref << endl;
	test04() = 10000;
	cout << "ref= " << ref << endl;
	cout << "ref= " << ref << endl;*/

	//int a = 10;
	自动转换为 int* const ref=&a;指针常量是指指针指向的内容不刻意修改(即为什么说引用不可以修改); 
	//int& ref = a;

	//ref = 20;//内部发现ref是引用自动转化为:*ref=20;

	//cout << "a= " << a << endl;
	//cout << "ref= " << ref << endl;

	//func4(a);

	//cout << "a= " << a << endl;
	//cout << "ref= " << ref << endl;

	//常量引用
	//使用场景:用来修饰形参,防止无操作

	//int a = 10;
	加上const之后,编译器将代码修改为   int temp=10;const int& ref=temp;
	//const int& ref = 10;//引用必须引一块合法的内存
	ref=20;//加入const之后变为只读,不可以修改
	
	/*int a = 1000;
	Print(a);
	cout << "a= " << a << endl;*/
	
	/*cout << "ret = " << func5(20, 20) << endl;
	cout << "ret = " << func5(100) << endl;*/

//函数站位参数

	func7(10);

	return 0;
}

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值