1.代码区
具有两个特点:
1是共享,即我们点开很多同一文件,但只执行那一段代码,并不会在生成另一份代码。
2是可读,即代码只可读,但不能写,不然会被修改数据,游戏金币
2.全局区
1.全局区中存放的变量
1.全局变量
#include<iostream>
int a=10;//全局变量
int main()
{
}
2.静态变量
static int a=10;
3.字符串常量
"hello world"
4.全局常量
#include<iostream>
const int a=10;//全局常量
int main()
{
}
2.不在全局区中存放的变量
1.局部常量
const int a=10;
2.局部变量
int a=10;
3.总结
1.总的来说学到了常量的分类吧,主要是字符串常量
2.c++在程序运行前分为全局区和代码区
3.栈区
栈区的注意事项:
1.不要返回局部变量的地址:因为局部变量存放在栈区,栈区的数据在函数执行完后自动释放,我们没法继续使用,可能你发现还能用一次,但那是因为编译器帮我们自动保留一次
4.堆区
#include <iostream>
using namespace std;
int* func()
{
int* a = new int(10);//new开辟一个空间放在堆区上,堆区是程序员区操控释放,new返回的是一个地址
return a;
}
int main()
{
int* p = func();
cout << *p << endl;//p=10
return 0;
}
5.new操作符
1.创建一小个空间
#include <iostream>
using namespace std;
int main()
{
int* p = new int(10);
cout << *p << endl;
delete p;//delete后面地址
return 0;
}
2.开辟一个一维数组
#include <iostream>
using namespace std;
int main()
{
int* array = new int[10];//意味开辟10个大小的数字
for (int i = 0; i < 10; i++)
{
array[i] = 100 + i;
}
for(int i=0;i<10;i++)
{
cout << array[i] << " ";
}
delete[] array;//我们要这样释放数组 ,加一个[]
return 0;
}
6.c++中的引用
1.引用必须初始化
int &b;//这样是不可以的,需要初始化
2.一旦初始化,就不可以更改
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a;
int c = 20;
b = c;//这是在赋值
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl;
return 0;
}
3.引用的作用
交换值时,除了用指针交换,还可以用引用的操作
#include <iostream>
using namespace std;
void swap(int& a, int& b)//这样做
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
swap(a, b);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
return 0;
}
原理是,void swap(int& a,int& b)这里面的a,b都相当于个别名,我们实际上就是再对原来的a,b做交换操作
4.引用的本质
1.引用实际上就是在整指针,具体来说是指针常量
#include <iostream>
int main()
{
int a = 10;
int& b = a;//实际上是int* const b=&a;
b = 20;//c++编译器发现b是引用,自动转化为*b=20,后续所有这种都是*b=val;
return 0;
}
7.函数的进阶
1.我们可以在定义函数那直接写等号
#include <iostream>
using namespace std;
int func(int a, int b = 20, int c = 30)//我们可以这样干
{
return a + b + c;
}
int main()
{
cout << func(10);//哈哈
return 0;
}
#include <iostream>
using namespace std;
int func(int a, int b = 20, int c = 30)
{
return a + b + c;
}
int main()
{
cout << func(10, 30, 30);
return 0;
}
//输出结果是70,不是60,说明我们传参的本领更强,可以吃掉我们在那定义的
2.有两点注意
1.直接在函数定义那赋值时,要从左到右写完
#include <iostream>
using namespace std;
int func(int a, int b = 20, int c )//这样不可以,因为b已经赋值,所以我们c也必须写上
{
return a + b + c;
}
int main()
{
cout << func(10, 30, 30);
return 0;
}
2.函数声明和定义只能一个有数
#include <iostream>
using namespace std;
int func(int a = 10, int b = 20, int c = 30);//我们不能这样做,怎么理解呢,编译器会混乱,到底是你那里面写的,还是那里面写的呢
int func(int a = 10, int b = 20, int c = 30)
{
return a + b + c;
}
int main()
{
cout << func();
return 0;
}
本文详细介绍了C++中的内存区域,包括代码区、全局区、栈区、堆区,强调了全局区中不同类型的变量以及栈区的注意事项。此外,还探讨了new操作符的使用,如创建小空间和一维数组。同时,文章讲解了C++中的引用,包括其初始化、不可更改性、作用以及本质——作为指针常量。最后,文章深入讲解了函数的进阶用法,如直接在函数定义中赋值及其注意事项。

被折叠的 条评论
为什么被折叠?



