您的位置:首页 > 编程语言 > C语言/C++

c++神奇的写法(一)

2017-09-23 20:18 148 查看
最近看《c++primer》一书,除了学到很多基础知识,还学到很多很神奇的写法,接下来就来总结一下,感觉就像黑魔法一样,虽然应该很少机会会用到:)



变量和基本类型

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++