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++的基本编程能力了。

相关推荐
大可不必了2 小时前
03 函数定义和调用
开发语言·python
I_belong_to_jesus2 小时前
C++关于分支预测的优化1
开发语言·c++·算法
承渊政道3 小时前
【Python编程—从入门到实践】(记分与闯关:用Python+Pygame,打造越战越精彩的太空大战!)
开发语言·python·pycharm·游戏程序·pygame
爱学习的程序媛3 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
Rabitebla3 小时前
【Linux】进程控制(十二) 自定义 Shell(二):内建命令与进程工作目录管理
linux·c++·笔记·学习·bash
eggwyw4 小时前
Anaconda安装卸载的详细流程指南
开发语言·python
码客-ygluu8 小时前
一个通用游戏数据服务器
c++·架构
another heaven9 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
SomeOtherTime10 小时前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
apcipot_rain10 小时前
C++转Java日记(10)
java·开发语言