new和malloc,const

int main()

{

int pc=(int*)malloc(sizeof(int));//强转

*pc=20;

free(pc);

int *pcpp=new int(10);

*pcpp=30;

delete pcpp;

}

1.new  关键字  malloc  函数 void*malloc(size_t)

2.new 系统计算大小  malloc人为计算所开辟的大小

3.new 返回值类型安全   malloc 返回值类型不安全(强转)

4.new 开辟内存还可以初始化  malloc 单纯的开辟内存

5.new[] 数组元素个数    malloc 传递数组整体大小

6.new 自由存储区    malloc 堆区

7.内存申请失败的时候,new抛出异常  malloc 会返回NULL空指针

8.new可以重载  malloc 不能重载

new:(1)operator new开辟内存(函数)

           (2)调用构造函数

9.new重定位  分配过的内存重新分配出去   malloc

int *p=new int;

char*a=new(p) char('a');

C:

const修饰的变量  常变量

编译查看常变量有没有做左值,其他处理方式和变量

C++:

const修饰的变量 常量

编译把用到常量的地方替换成常量初始化的值

1.常量一定要初始化

2.常量一定不允许修改

int main()

{

const int a;

int *p=&a;//C 错  间接修改a的值,C+没有初始化是错的

*p=20;

return 0;

}

int main()

{

const int a=10;

int arr[a];//int arr[10];  C错 C++对

return 0;

}

const的用法:

一.const变量

1.全局变量

const int gdata=10;//本地文件

2.局部变量

const int ldata=20;//常量

3.成员变量

const int mdata=20;//类成员方法初始化

二 const类成员

常方法

普通-->  type *const this

            const type*const this

常对象只能调动常方法

猜你喜欢

转载自blog.csdn.net/m0_43407388/article/details/107689070
今日推荐