C++ 回忆录4

来源:互联网 发布:被子布料差异知乎 编辑:程序博客网 时间:2024/04/29 16:02

1.运算符,象+-*/% ,,注意其优先级,结合性.

2.等值测试

if(val==true){.............}

由于bool 可以被convert to 算数类型,false->0,true->1,

所以这个比较会被转化成

if(val==1){.............}

其实简单的就是

if(val){..............}

就不会有风险了.


3.<< <

cout<<10<4;//error. IO 中的  <<   运算符跟关系运算符中的<<有相同的优先级别,所以会先执行cout<<10, 返回cout 跟4比较


4.= 赋值运算符

赋值运算  返回左边的运算子,  低优先级别.

int i=getValue();

while(i!=42)

{

  //do sth

i=getValue();

}

/// 可以写成

while((i=getValue())!=42) //由于低优先级,所以括号不能少

{

//do sth.....

}

右结合性

int i,j;

i=j=0;

5 ++ --

have 2 version :prefix,postfix.

int i=0;

int j=i++;// j=0,i=1,需要一个生成一copy 赋给j,然后自己+1

so ,prefix do less work. it increments the value and returns the incremented version.

postfix operator must store the original value so that it can return the unincremented value  as it's result.

base on this fact we can write

vector<int>::iterator it=ivec.begin();

while(it!=ivc.end())

{

 cout <<*it++<<endl;//  ++的优先级高于*, 但是 后缀的++返回的是未++之前的值,所以可以安全的打印所有的值....

}

6.-> arrow operator

调用一个对象的方法我们是

Object a;

a.function(..); //使用.点运算符

如果我们只用这个对象的指针,

Object * pA;

那就需要先解引用. (*pA).function(...) ,然后才调用到这个对象. 注意由于 * 比. 优先级别低,所以括号不能少,

而最后的办法是使用->

pA->function(....) //好看多了..



7 sizeof

 返回 多少个byte.

sizeof char or expression of type char is guaranteed to be 1.

sizeof reference type 返回这个引用所引用的对象的内存大小.

sizeof   pointer, 返回的是容纳这个pointer 所需要的空间. 但不只这个pointer 所指向的对象的空间.

sizeof array 返回整个数组的大小. 正因为这个特性我们可以这样算数组有多少个元素.

int len=sizeof(arr)/sizeof(*arr)  or int len=sizeof(arr)/sizeof(arr[0]);

8 ; 分号运算符

the expression ar evaluated from left to right.the result is the rightmost expression;


10 new delete

new delete 是成套使用的

string str="";

delte str;// error.

string * str=new string("afasf");

delte str;//ok


如果是数组,需要加[];

int  * k=new int[10];

delete [] k;// can not be delte k;


int *  p=0;

delete p;//还是合法的.


int * kk=&x;

delete kk;// 虽然做了delete 的回收动作,但其实kk 还是指向那个内存地址的,will became dangling pointer.只是那内存地址所在内存被回收了. 如果此时还去引用kk,将会有错误.所以best practice is

delete kk;

kk=0;// 将他指向0.



const int * pci=new const int(1024) ;//const new

delete pci;//ok 的 虽然pci 指向的值1024 不能被改变,但还是可以delete 回收的




原创粉丝点击