#includeusing namespace std; //1.new 的基本语法 int* func() { //在堆区创建一个整型数据 //new返回的是 该数据类型的指针 int* p = new int(10); return p; } void test9() { int* p = func(); cout << *p << endl; cout << *p << endl; cout << *p << endl; delete p; //cout << *p << endl; } //2.在堆区利用new开辟数组 void test9_2() { //在堆区创建10整型的数组 int* arr = new int[10];//10代表数组有10个元素 for (int i = 0; i < 10; i++) { arr[i] =( i + 1 ) * 100;//给10个元素赋值 } for (int j = 0; j < 10; j ++) { cout << arr[j] << endl; } //释放堆区数组 //释放数组时,要加[]才行 delete[] arr; } void test9_3() { //引用的基本语法 //数据类型 &别名 = 原名; int a = 10; //创建引用 int& b = a; cout << "a = " << a << endl; cout << "b = " << b << endl; b = 100; cout << "a = " << a << endl; cout << "b = " << b << endl; } //引用传递[与地址传递效果一致] void mySwap03(int &a,int &b) { int temp = a; a = b; b = temp; } //引用做函数的返回值 //1.不要返回局部变量的引用[以下有误] int& test9_4() { int a = 10;//局部变量存放在四区中的 栈区 return a; } //2.函数调用可以作为左值 int& test9_5(){ static int a = 10;//静态变量,存放在全局区,全局区上的数据在程序结束后系统释放 return a; } //如果函数的返回值是引用,这个函数调用可以作为左值 void showValue(const int &value) { //value = 1000;//不可修改 cout << "value = " << value << endl; } void test9_6() { //常量引用 //使用场景:用来修饰形参,防止误操作。 //int a = 10; //加上const之后,编译器将代码修改 int temp = 10; int & ref = temp; const int& ref = 10;//引用必须引一块合法的内存空间 //ref = 20;//加入const后变为只读,不可修改 int a = 100; showValue(a); cout << "a = " << a << endl; } int main9() { //test9(); //test9_2(); //test9_3(); test9_6(); system("pause"); return 0; }



