[关闭]
@gump88 2016-08-13T12:47:58.000000Z 字数 3822 阅读 1042

title: Tips From C++ Primer

Tips From C++ Primer

date: 2016-06-06 20:31:12

C++

Tips

  1. const vector<int> nines = (10,9);
  2. //error,cit2是一个常量迭代器,自己的值不可以改变,但是可能改变迭代器指向的值
  3. const vector<int> :: iterator cit2 = nines.begin();
  4. //const_iterator表明指向的值不可以改变,但是迭代器的值可以改变
  5. vector<int> ::const_iterator it = nines.begin();
  6. //error
  7. *it = 10;
  8. //correct
  9. ++it;
  1. string st3("Hello world!");
  2. char *str = st3;//compile error
  3. const char *str = st3.c_str();//success,这里st3.c_str()返回的是const char类型的数组,避免修改该数组。
  1. int ia[3][4];
  2. int (*ip)[4] = ia;//表明是一个指向4个int类型数组的指针
  3. ip = &ia[2]; //重新指向第三个int型数组ia[2]
  4. //注意下面的写法表示的意义是不一样的
  5. int *ip[4]; //表明ip指向一个int 型指针数组,array of pointers to int
  6. int (*ip)[4]; //表明ip指向一个int 型数组,pointer to an array of 4 ints
  1. vector<int> ivec;
  2. vector<int>::iterator iter = ivec.begin();
  3. while(iter != ivec.end())
  4. cout<<*iter++<<endl;

解引用操作的优先级低于后自增操作,所以上述表达式先后++,然后进行解引用。
后自增的优先级高于前自增点操作的优先级高于解引用操作优先级

  1. #if 条件成立
  2. ...
  3. #elif 条件成立
  4. ..
  5. #else 否则条件成立
  6. ...
  7. #endif 结束条件编译

判断是否定义过宏

  1. #if defined(MACRO1)
  2. ...
  3. #if !defined(MACRO2)
  4. ...
  5. #endif

还可以使用下面的定义,实现功能等效上面

  1. #ifdef MACRO
  2. ...
  3. #ifndef MACRO
  4. ...
  5. #endif
  1. #define String1 char*
  2. typedef char *String2;
  3. String1 str1,str2;//等价于
  4. char *str1;
  5. char *str2;
  6. String2 str1,str2;//等价于
  7. char *str1,str2;//等价于
  8. char *str1;
  9. char str2;
  1. int a = 1,b = 2,c = 3;
  2. int a = a + b, a + c;
  3. cout<<a<<endl;
  4. //输出是5
  1. dynamic_cast <new_type> (expression)
  2. reinterpret_cast <new_type> (expression)
  3. static_cast <new_type> (expression)
  4. const_cast <new_type> (expression)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注