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

来源:互联网 发布:值机软件 编辑:程序博客网 时间:2024/06/08 19:54

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指针后赋值为NULL0是个好习惯。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;//1int *p2=(int*)&i;//2*p2=20;cout<<"i:"<<i<<endl;cout<<"*p2:"<<*p2<<endl;//const_castint *p3=const_cast<int*>(&i);//3,解除const限定,只能对指针和引用*p3=30;cout<<"i:"<<i<<endl;cout<<"*p3:"<<*p3<<endl;//static_castint num1=5, num2=2;//double ret=double(num1)/num2;double ret=static_cast<double>(num1)/num2;//强制类型转换cout<<"ret:"<<ret<<endl;
原创粉丝点击