一、结构体
结构体属于用户自定义的数据类型。
1.1 创建结构体
语法:struct 结构体名 {成员列表};
,注意大括号后的分号!
struct Student {
string name;
int age;
int score;
};
Student s1; // 声明一个Student类型的变量。如果是C需要加上struct关键字
Student s1 = {"Bob", 18, 98}; // 赋值
/* 也可以定义的时候创建变量 */
struct Student {
string name;
int age;
int score;
} s1;
1.2 结构体指针
使用结构体指针时,访问成员可使用 ->
符号。p->name
与 (*p).name
等价。
#include <iostream>
#include <string>
using namespace std;
struct Node {
string name;
int val;
};
int main() {
Node head = {"abc", 2};
cout << head.name << endl;
Node *p = &head;
cout << (*p).name << endl;
cout << p->name << endl; // 与上方等价
return 0;
}
1.3 结构体构造函数
struct node {
string name;
int age;
double score;
// 以下是构造函数的几种写法
// 写法一
node (string a, int b, double c) {
name = a;
age = b;
score = c;
}
// 写法二
node (string a, int b, double c) : name(a), age(b), score(c) {}
}
二、内存分区
内存大致分为四个区域:
- 代码区:存放函数体的二进制代码(共享+只读)
- 全局区:全局区内的变量在程序编译阶段已经分配好内存空间并初始化。这块内存在程序的整个运行期间都存在。存放全局变量,静态变量以及常量(字符串常量和用const修饰的全局变量)
- 栈区:由系统进行内存的管理。主要存放函数的参数以及局部变量。在函数完成执行,系统自行释放栈区内存,不需要用户管理
- 堆区:由编程人员手动申请,手动释放,若不手动释放,程序结束后由系统回收,生命周期是整个程序运行期间。使用malloc或者new进行堆的申请
不同区域存放的数据,给予不同的生命周期。
程序运行前只有代码区和全局区。运行后有栈区和堆区。栈区中的变量在运行结束之后会被回收,因此不要返回局部变量的地址。在C++中主要利用new在堆区开辟内存。
2.1 new操作符
基本语法:new 数据类型
int *p = new int(10); // new返回一个该数据类型的指针
如果想释放堆区的数据,利用关键字 delete
delete p;
利用new开辟一个长度为10的数组
int *arr = new int[10];
delete[] arr; // 释放堆区数组
2.2 malloc操作符
#include <iostream>
#include <cstdlib> // malloc定义在这个头文件里
using namespace std;
int main() {
// 给 int 型指针分配四个字节
int* ptr = (int*) malloc(sizeof(int));
// assign the value 5 to allocated memory
*ptr = 5;
cout << *ptr;
return 0;
}
// Output: 5
数组案例:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
// allocate 5 int memory blocks
int* ptr = (int*) malloc(5 * sizeof(int));
// check if memory has been allocated successfully
if (!ptr) {
cout << "Memory Allocation Failed";
exit(1);
}
cout << "Initializing values..." << endl << endl;
for (int i = 0; i < 5; i++) {
ptr[i] = i * 2 + 1;
}
cout << "Initialized values" << endl;
// print the values in allocated memories
for (int i = 0; i < 5; i++) {
// ptr[i] and *(ptr+i) can be used interchangeably
cout << *(ptr + i) << endl;
}
// deallocate memory
free(ptr);
return 0;
}
三、引用
3.1 引用的基本操作
作用:给变量起别名
语法:数据类型 &别名 = 原名
引用必须要初始化,即 int &b;
是错误的。且引用初始化后,就不可以更改了。
引用的本质是一个指针常量(例如是int * const
而不是 const int *
)