关键字之操作符(运算符)

C++新增操作符(运算符):
new:分配内存空间
delete:释放内存空间
const_cast:
static_cast:
dynamic_cast:
reinterpret_cast:
this:
operator:
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq:各种运算符替代名

1.new和delete

int *ptr = new int;
*ptr = 10;

delete ptr;//delete ptr之后,只是释放了指针指向的内存空间。ptr并不会自动被置为NULL,指针还存在,同时还指向了之前的地址。
ptr = NULL;//C++标准规定:delete空指针是合法的,没有副作用,所以我们在Delete指针后赋值为NULL或0是个好习惯。
delete ptr;//if set ptr equalto NULL after delete ptr, delete ptr again will cause no problem, if not, that will cause double delete.

int *ptr2 = new int[10];
delete []ptr2;//[]-->表示批量删除,与new []保持一致
ptr2 = NULL;

2.const_cast、static_cast

const int i=10;
//int *p=&i; //error

//const-->const
//非const-->const
//const 不能-->非const 

const int* ptr=&i;//1
int *p2=(int*)&i;//2
*p2=20;
cout<<"i:"<<i<<endl;
cout<<"*p2:"<<*p2<<endl;

//const_cast
int *p3=const_cast<int*>(&i);//3,解除const限定,只能对指针和引用
*p3=30;
cout<<"i:"<<i<<endl;
cout<<"*p3:"<<*p3<<endl;

//static_cast
int num1=5, num2=2;
//double ret=double(num1)/num2;
double ret=static_cast<double>(num1)/num2;//强制类型转换
cout<<"ret:"<<ret<<endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值