目录
一、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;
}