网站首页 > 基础教程 正文
C++11 和 C++17 是 C++ 语言的两个重要版本,它们引入了许多新的特性和改进。以下是对这两个版本主要特性的介绍:
C++11 特性
C++11 是一个重大更新,添加了许多新特性,使得 C++ 更加现代化和易用。以下是一些关键特性:
自动类型推导 (auto):
auto i = 10; // 编译器会自动推导出 i 的类型为 int
范围 for 循环:
std::vector<int> vec = {1, 2, 3, 4};
for (auto& v : vec) {
std::cout << v << " ";
}
Lambda 表达式:
auto add = [](int a, int b) { return a + b; };
std::cout << add(2, 3); // 输出 5
智能指针:
std::unique_ptr<int> ptr = std::make_unique<int>(10);
std::shared_ptr<int> sptr = std::make_shared<int>(20);
右值引用和移动语义:
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = std::move(vec1); // vec1 的资源被移动到 vec2
nullptr 关键字:
int* p = nullptr; // 用于替代 NULL
线程库:
std::thread t([]{ std::cout << "Hello from thread"; });
t.join();
constexpr 关键字:
constexpr int square(int x) { return x * x; }
int arr[square(3)]; // arr 的大小为 9
静态断言 (static_assert):
static_assert(sizeof(int) == 4, "Integers must be 4 bytes");
新标准库容器:
- std::array
- std::unordered_map
- std::unordered_set
C++17 特性
C++17 引入了一些增量改进和新特性,进一步增强了 C++ 的功能和易用性。以下是一些主要特性:
结构化绑定:
std::tuple<int, double, std::string> t(1, 2.3, "hello");
auto [i, d, s] = t;
if 和 switch 的初始化:
if (int x = f(); x > 0) {
// 使用 x
}
switch (int y = g(); y) {
case 1:
// 使用 y
break;
}
std::optional:
std::optional<int> opt = 42;
if (opt) {
std::cout << *opt; // 输出 42
}
std::variant 和 std::visit:
std::variant<int, float> v = 42;
std::visit([](auto&& arg) { std::cout << arg; }, v); // 输出 42
std::any:
std::any a = 1;
a = std::string("hello");
std::cout << std::any_cast<std::string>(a); // 输出 hello
折叠表达式:
template<typename... Args> auto sum(Args... args) {
return (args + ...); // 折叠表达式
}
内联变量:
inline int x = 42;
std::filesystem 库:
std::filesystem::path p = "/path/to/file";
std::cout << std::filesystem::exists(p);
constexpr 的改进:
constexpr int factorial(int n) {
return n <= 1 ? 1 : (n * factorial(n - 1));
}
std::string_view:
std::string_view sv = "Hello, world";
std::cout << sv.substr(0, 5); // 输出 Hello
总结
C++11 和 C++17 都引入了许多新特性,使得 C++ 变得更强大和灵活。C++11 带来了大量的基础性改进和新特性,而 C++17 则是在此基础上进行了一些增量改进和优化。了解和使用这些新特性,可以帮助开发者编写更高效和现代化的 C++ 代码。
- 上一篇: C++无条件转移控制 无条件转移指令包括
- 下一篇: C++入门到精通(第三课 程序的选择执行)
猜你喜欢
- 2024-11-03 有c语言基础 学c++应付期末考试要多久?
- 2024-11-03 C++模拟ATM自动取款机 atm取款机c++代码
- 2024-11-03 维塔士Andy Fong:Switch游戏优化经验分享
- 2024-11-03 盘点c++几种常见的设计模式及具体实现
- 2024-11-03 C++入门到精通(第三课 程序的选择执行)
- 2024-11-03 C++无条件转移控制 无条件转移指令包括
- 2024-11-03 C++选择结构,让程序自动进行决策
- 2024-11-03 C++有哪些新特性 c++的新特性
- 2024-11-03 3分钟带你玩转循环——图解if…else和switch
- 2024-11-03 《C++程序设计》学习 c++程序设计入门
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)