c++神奇的写法(一)
2017-09-23 20:18
148 查看
最近看《c++primer》一书,除了学到很多基础知识,还学到很多很神奇的写法,接下来就来总结一下,感觉就像黑魔法一样,虽然应该很少机会会用到:)
注意点:
auto定义的变量必须有初始值
使用auto也能在一条语句中声明多个变量,但是他们的类型必须相同
auto未必会推断出正确的类型
当引用被作为初始值时,编译器会以引用所指的类型作为auto的类型
auto一般会忽略顶层const,但会保留底层const
如果希望保留引用或顶层const的话,要明确指出来
(c++11标准)
注意点:
不会忽略顶层const和引用
有些表达式会给decltype一个引用的类型
decltype((variable))的结果永远是引用,decltype(variable)的结果只有当variable是一个引用时才是引用,因为(variable)会看成是一个表达式
*当我们对某个函数用decltype时,得到的是function type,而不是a pointer to function
注意点:定义在iterator头文件
注意点:不允许使用一个数组初始化另外一个数组,也不允许使用vector对象初始化数组,但是可以用数组来初始化vector对象
direct initialized(和copy initialized相对的那个)
list initialized
value initialized
auto initialized
变量和基本类型
auto类型说明符
作用:能让编译器替我们去分析表达式的类型注意点:
auto定义的变量必须有初始值
使用auto也能在一条语句中声明多个变量,但是他们的类型必须相同
auto未必会推断出正确的类型
当引用被作为初始值时,编译器会以引用所指的类型作为auto的类型
auto一般会忽略顶层const,但会保留底层const
如果希望保留引用或顶层const的话,要明确指出来
int a = 1,&b = a; const int c = 1,&d = c; auto x_1 = a; //x_1 is int auto x_2 = b; //x_2 is int auto x_3 = c; //x_3 is int auto x_4 = d; //x_4 is int auto x_5 = &a; //x_5 is a pointer to int auto x_6 = &c; //x_6 is a pointer to const int const auto x_7 = d; //x_7 is const int auto &x_8=c; //x_8 is a reference to const int const auto &x_9=32; //x_9 is a reference to const int
(c++11标准)
decltype类型指示符
作用:希望从表达式推断出要定义的类型,但不用表达式的值初始化变量注意点:
不会忽略顶层const和引用
有些表达式会给decltype一个引用的类型
decltype((variable))的结果永远是引用,decltype(variable)的结果只有当variable是一个引用时才是引用,因为(variable)会看成是一个表达式
*当我们对某个函数用decltype时,得到的是function type,而不是a pointer to function
字符串、向量和数组
标准库函数begin()和end()
作用:返回指向首指针和尾后指针注意点:定义在iterator头文件
使用数组初始化vector对象
步骤:int int_arr[ ]={0,1,2,3,4,5}; vector<int> ivec(begin(int_arr),end(int_arr));
注意点:不允许使用一个数组初始化另外一个数组,也不允许使用vector对象初始化数组,但是可以用数组来初始化vector对象
用new动态分配内存
default initialized(会导致built-in-type对象有undefined值)int *pi = new int; // pi指向uninitialized int string *ps = new string; // ps指向空string
direct initialized(和copy initialized相对的那个)
int *pi = new int(1024); string *ps = new string(10,'9');
list initialized
vector<int> *pv = new vector<int>{0,1,2,3,4,5};
value initialized
string *ps = new string(); // ps指向空string int *pi = new int(); // pi指向0
auto initialized
auto p1 = new auto(obj);
相关文章推荐
- C++中几种常见的单例模式写法。
- C++ #include头文件写法的区别
- 【cocos2d-x从c++到js】05:John Resiq的继承写法解析
- C++中为什么有delete[]这种写法?
- 数据库编程中针对c++的构造sql语句的写法
- ue4 c++ 接口写法
- perl Exporter一些神奇写法
- 【C++模版之旅】神奇的Traits
- C/C++语言中#的神奇作用:把宏参数字符串化/贴合宏参数
- linux c++ 循环消息队列写法
- C/C++/Java for语句规范写法浅析(二重及以上循环)
- C++ 中Hello World的一种写法
- C++可变参数写法
- C++面试中string类的一种正确简明的写法
- memcpy内存拷贝函数的写法c++代码实例及运行结果
- Effective Modern C++ 笔记(二)——写法规范
- C++友元函数神奇的friend
- perl Exporter一些神奇写法
- cmakelists对于c项目和c++项目的写法
- void* shu_zu_ming[n][m] 传参的函数定义写法 【C++】