C++~07补充

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新特性你了解哪些?

  1. 智能指针

  2. nullptr

  3. 类型推导

  4. 类型转换

  5. 继承构造

  6. array

  7. override

  8. 初始化构造、窄化

  9. for-each(增强型for循环)

10.constexpr

......

如果没有难到你恭喜你已具备现代C++的基本编程能力了。

相关推荐
hold?fish:palm1 小时前
40 二叉树的直径
c++·leetcode
解决小子2 小时前
【虚幻引擎】【C++】【GAS框架】构建角色基类、属性集、数值钳制
c++·笔记·游戏引擎·虚幻·gas·能力系统
lunar_coder3 小时前
【C++】如何解决智能指针的析构函数,如何实现shared_ptr的引用计数以及解决shared_ptr的循环引用
c++·1024程序员节
白白白小纯3 小时前
C++进阶.多态
c++
2401_885885044 小时前
国际语音C#接口怎么写?.NET环境下实现国际语音验证码批量下发
开发语言·c#·.net
程序猿乐锅4 小时前
【从0-1学习Python | 第七篇】Python 面向对象基础
开发语言·笔记·后端·python·学习·1024程序员节
Wang's Blog4 小时前
Java 项目实战: 交友项目 - 查询圈子个人动态:查询我的动态需求分析
java·开发语言·交友
凯瑟琳.奥古斯特4 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展