C++基础学习

目录

一、new 的使用

1.开辟整形指针

2.开辟数组

二、引用&的用法:

引用的注意事项:

引用的本质:指针常量

应用:常量引用

三、函数默认参数:


一、new 的使用

1.开辟整形指针

int *p=new int(10);//*p=10,10是初始值

释放:delete p;

2.开辟数组

int *arr=new int[10];//开辟10位数的数组

释放:delete [ ]arr;

二、引用&的用法:

int &b=a;

引用的注意事项:

1.必须初始化: int &b=a;   //int &b;错误

2.引用一旦初始化不可以再更改:int &b=a;再int &b=c;错误

#include<iostream>
using namespace std;
int& test()
{
	static int a = 10;//静态变量,存于全局区,系统结束后释放
	return a;
}
int  main()
{
	int& temp = test();
	cout << temp << endl;
	cout << temp << endl;
	//cout << a << endl;错误 
	test() = 100;//如果函数的返回值是引用,这个函数的调用可以作为左值,即a=100
	cout << temp << endl;
	system("pause");
}

引用的本质:指针常量

#include<iostream>
using namespace std;
int func(int & ref)
{
	ref = 100;//ref是引用*ref=100;
	return 0;
}
int  main()
{
	int a = 10;
	int& ref = a;//自动转换为int* const ref =&a;
	ref = 20;//等效转换 *ref=20;
	cout << "a:" << a << endl;
	cout << "ref:" << ref << endl;
	func(a);
	cout << "a:" << a << endl;
	cout << "ref:" << ref << endl;
	return 0;
	system("pause");
}

输出结果:

a:20
ref:20
a:100
ref:100

应用:常量引用

#include<iostream>
using namespace std;

void print(const int & ref)//加const防止误操作修改实参
{
	cout<<ref<<endl;
}
int  main()
{
    //int &m=10;错误
    const int &m=10;//正确系统自动temp=10;const int &m=temp;
    //m=100;错误,加const不可修改
	int a = 10;
	int& ref = a;
	print(a);
	return 0;
}

三、函数默认参数:

函数默认参数

1.赋默认值时从某个位置开始后面必须全有

2.函数声明中有默认值则实现中不能有默认值

#include<iostream>
using namespace std;
int func(int a, int b = 10, int c = 20);
int func(int a,int b,int c)//如果自己输入则使用输入,否则使用默认值
{
	return a+b+c;
}
int  main()
{
	cout << func(10) << endl;//输出40
	cout << func(10,20) << endl;//输出50
	cout << func(10, 20) << endl;//输出50
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值