1 new操作符
C++中利用==new==操作符在堆区开辟数据
堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符 ==delete==
语法:new 数据类型
利用new创建的数据,会返回该数据对应的类型的指针
int* func(){int* a = new int(10);return a;}int main(){int* p = func();cout << *p << endl;cout << *p << endl;//利用delete释放堆区数据delete p;//cout << *p << endl; //报错,释放的空间不可访问system("pause");return 0;}
开辟数组
int main(){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 后加 []delete[] arr;system("pause");return 0;}
总结:
堆区数据由程序员管理开辟和释放
堆区数据利用new关键字进行开辟内存
2 引用的基本使用
作用: 给变量起别名
语法: 数据类型 &别名 = 原名
int main(){int a = 10;int &b = a;cout << "a = " << a << endl;cout << "b = " << b << endl;b = 100;cout << "a = " << a << endl;cout << "b = " << b << endl;system("pause");return 0;}
引用注意事项
- 引用必须初始化
- 引用在初始化后,不可以改变
示例:
int main(){int a = 10;int b = 20;//int &c; //错误,引用必须初始化int& c = a; //一旦初始化后,就不可以更改c = b; //这是赋值操作,不是更改引用cout << "a = " << a << endl;cout << "b = " << b << endl;cout << "c = " << c << endl;system("pause");return 0;}
3 引用做函数参数
作用:函数传参时,可以利用引用的技术让形参修饰实参
优点:可以简化指针修改实参
//值传递void mySwap01(int a, int b){int temp = a; a = b; b = temp;}//地址传递void mySwap02(int* p1, int* p2){int temp = *p1; *p1 = *p2; *p2 = temp;}//3. 引用传递void mySwap03(int& a, int& b){int temp = a; a = b; b = temp;}int main(){int a = 10;int b = 20;//mySwap01(a, b);//cout << "a:" << a << " b:" << b << endl;//mySwap02(&a, &b);//cout << "a:" << a << " b:" << b << endl;mySwap03(a, b);cout << "a:" << a << " b:" << b << endl;system("pause");return 0;}
4 引用做函数返回值
//返回局部变量引用int& test01(){int a = 10; //局部变量return a;}//返回静态变量引用int& test02(){static int a = 20;return a;}int main(){//不能返回局部变量的引用int& ref = test01();cout << "ref = " << ref << endl;cout << "ref = " << ref << endl;//如果函数做左值,那么必须返回引用int& ref2 = test02();cout << "ref2 = " << ref2 << endl;cout << "ref2 = " << ref2 << endl;test02() = 1000;cout << "ref2 = " << ref2 << endl;cout << "ref2 = " << ref2 << endl;system("pause");return 0;}
5 引用的本质
//发现是引用,转换为 int* const ref = &a;void func(int& ref){ ref = 100; // ref是引用,转换为*ref = 100}int main(){int a = 10;//自动转换为 int* const ref = &a; 指针常量是指针指向不可改,也说明为什么引用不可更改int& ref = a;ref = 20; //内部发现ref是引用,自动帮我们转换为: *ref = 20;cout << "a:" << a << endl;cout << "ref:" << ref << endl;func(a);system("pause");return 0;}
6 常量引用
作用:常量引用主要用来修饰形参,防止误操作
在函数形参列表中,可以加==const修饰形参==,防止形参改变实参
//引用使用的场景,通常用来修饰形参
void showValue(const int& v)
{
//v += 10;
cout << v << endl;
}
int main()
{
//int& ref = 10; 引用本身需要一个合法的内存空间,因此这行错误
//加入const就可以了,编译器优化代码,int temp = 10; const int& ref = temp;
//const int& ref = 10;
//ref = 100; //加入const后不可以修改变量
//cout << ref << endl;
//函数中利用常量引用防止误操作修改实参
int a = 100;
showValue(a);
system("pause");
return 0;
}
