1. nullptr(掌握)
在传统的C和C++中,空指针使用的关键字是NULL,但是存在下面的问题:
#include <iostream>`
`using` `namespace std;`
`void` `func(int i)`
`{`
` cout <<` `"A"` `<< i << endl;`
`}`
`void` `func(char* i)`
`{`
` cout <<` `"B"` `<< i << endl;`
`}`
`int` `main()`
`{`
`func(NULL);` `// A0`
`return` `0;`
`}`
`
在C++11中,使用新的关键字nullptr代替NULL,可以解决上述问题:
#include <iostream>`
`using` `namespace std;`
`void` `func(int i)`
`{`
` cout <<` `"A"` `<< i << endl;`
`}`
`void` `func(char* i)`
`{`
` cout <<` `"B"` `<< i << endl;`
`}`
`int` `main()`
`{`
`func(nullptr);` `// B`
`return` `0;`
`}`
`
2. 类型推导(熟悉)
使用关键字auto可以自动推导变量类型。
#include <iostream>`
`using namespace std;`
`int main()`
`{`
` auto i = 5; // auto会被自动推导为int`
` cout << i << endl;`
` auto i2 = new auto(5); // auto会被自动推导为int*`
` cout << i2 << " " << *i2 << endl;`
` delete i2;`
` return 0;`
`}`
`
C++11中引入了decltype关键字,可以推导表达式。推导的过程中只推导类型计算,不进行数值计算。
#include <iostream>`
`using namespace std;`
`int main()`
`{`
` auto i = 5;`
` auto i2 = 5.4;`
` decltype(i+i2) i3 = 3.14; // 推导表示的类型作为i3的类型`
` cout << i3 << endl;`
` return 0;`
`}`
`
3. 至此C++你已基本会用了,那么扪心自问你都学会了吗(重点)
C++11新特性你了解哪些?
-
智能指针
-
nullptr
-
类型推导
-
类型转换
-
继承构造
-
array
-
override
-
初始化构造、窄化
-
for-each(增强型for循环)
10.constexpr
......
如果没有难到你恭喜你已具备现代C++的基本编程能力了。