// int* p = new int (10) 是在堆区创建一个int型的内存,并赋值为10;
// int *p = new int[10] 是创建10个int型的内存;
// new int ()是一个int * 地址
//引用 int&ref =a; ----> int * const ref=&a;
// ref = 20;-------> *ref =20; 解引用
//引用就是指针常量 指针指向不可改,内容可以改
#include <iostream>
using namespace std;
#include <string>
// c++代码运行前分为 全局区、代码区
// 不要返回局部变量地址
int* func(int b)//形参数据放在栈区,函数执行完直接释放
{
b = 100;
int a = 10;//局部变量 存放在栈区,函数执行完直接释放
return &a;
int* p = new int(10);//需要关键字 new,new得到的是指针
return p;
}
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;//释放数组
}
//全局变量
int g_a = 10;
int g_b = 10;
//全局常量
const int c_g_a = 10;
//引用传递
void swap(int &a, int &b)引用传递与地址传递一样,改变实参
{
int temp = a;
a = b;
b = temp;
}
// 不要返回局部变量引用
int& test()
{
static int a = 10;// 除非有static 就可以返回局部变量引用,
return a; // static在全局区,不会和栈区一样函数执行完就消失;他会在程序结束消失
}
//常量引用 修饰形参防止误操作
void show(const int &val)
{
val=1000;/不正确,如果没有const 实参也会改变
cout<<val<<endl;
}
int main()
{
int b = 10;
int* p=func(b);
int* p = func(1);
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
delete p;//释放内存 : delete地址
cout << *p << endl;
//局部变量
int a = 10;
int b = 10;
//静态变量
static int s_a = 10;
static int s_b = 10;
//const修饰的局部变量
const int c_l_a = 10;
cout << "a的地址" << (int)&a << endl;
cout << "b的地址" << (int)&b << endl;
cout << "g_a的地址" << (int)&g_a << endl;//全局 静态放在一起
cout << "g_b的地址" << (int)&g_b << endl;
cout << "s_a的地址" << (int)&s_a << endl;
cout << "s_b的地址" << (int)&s_b << endl;
cout << "字符串地址" << (int)&"hello" << endl;
cout << "const修饰的全局变量地址" << (int)&c_g_a << endl;
cout << "const修饰的局部变量地址" << (int)&c_l_a << endl;
//全局区 有 全局变量、全局常量、static静态、字符串,在程序执行完才释放,点击 X
//栈区 函数执行完就消失
//引用 给变量起其他名字
// 数据类型 &别名=原名
int a = 10;
int& b = a; //a b都指向同一块内存
//引用只能用一次
//函数作为左值,必须返回引用
test() =1000;
//常量引用 修饰形参防止误操作
const int &ref=10;// ---->int temp =10; const int & ref =temp;
// int &ref=10 不可以
int a=10;
show(const int &val);
system("pause");
return 0;
}
C++学习路程 22/3/7 PM 19:31
于 2022-03-07 22:25:44 首次发布