C++ 中 new 的用法

C++ 关键字 - new 的用法·

https://www.runoob.com/cprogramming/c-standard-library.html

位于C++ 标准库 #include

描述·

new其实就是告诉计算机开辟一段新的空间,但是和一般的声明不同的是,new开辟的空间在堆上,而一般声明的变量存放在栈上。通常来说,当在局部函数中new出一段新的空间,该段空间在局部函数调用结束后仍然能够使用,可以用来向主函数传递参数。

另外需要注意的是,new的使用格式,new出来的是一段空间的首地址。所以一般需要用指针来存放这段地址。

一般用 delete 回收这个存储空间。

语法规则·

1
2
3
4
5
6
7
int *x = new int;         //开辟一个存放整数的存储空间,返回一个指向该存储空间的地址(即指针)

int *a = new int(100); //开辟一个存放整数的空间,并指定该整数的初值为100,返回一个指向该存储空间的地址

char *b = new char[10]; //开辟一个存放‘字符数组’(包括10个元素)的空间,返回首元素的地址

float *p=new float (3.14159);//开辟一个存放单精度数的空间,并指定该实数的初值为//3.14159,将返回的该空间的地址赋给指针变量p

用法·

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
using namespace std;
int example1()//新建函数1
{
//可以在new后面直接赋值
int *p = new int(3);
//也可以单独赋值
//*p = 3;

//如果不想使用指针,可以定义一个变量,在new之前用“*”表示new出来的内容
int q = *new int;
q = 1;
cout << q << endl;

return *p;
}

int* example2()//新建函数2
{
//当new一个数组时,同样用一个指针接住数组的首地址
int *q = new int[3];
for(int i=0; i<3; i++)
q[i] = i;

return q;
}

struct student
{
string name;
int score;
};


student* example3()//新建函数3
{
//这里是用一个结构体指针接住结构体数组的首地址
//对于结构体指针,个人认为目前这种赋值方法比较方便
student *stlist = new student[3]{{"abc", 90}, {"bac", 78}, {"ccd", 93}};

return stlist;
}


int main()//主函数
{
int e1 = example1();
cout <<"e1: "<< e1 << endl;

int *e2 = example2();
for(int i=0; i<3; i++)
cout << e2[i] << " ";
cout << endl;


student *st1 = example3();

for(int i=0; i<3; i++)
cout << st1[i].name << " " << st1[i].score << endl;



return 0;
}

返回值·

该函数返回一个存储空间的首地址(指针)。一般用 delete 回收这个存储空间。