news 2026/5/1 5:01:54

【20天学C++】Day 17: C++11新特性

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【20天学C++】Day 17: C++11新特性

【20天学C++】Day 17: C++11新特性

📅 学习时间:4-5小时
🎯 学习目标:掌握C++11重要新特性
💡 难度:★★★★☆


1. auto类型推导

#include<iostream>#include<vector>#include<map>usingnamespacestd;intmain(){// 基本类型autoi=10;// intautod=3.14;// doubleautos="hello";// const char*autostr=string("hello");// string// 容器迭代器vector<int>v={1,2,3,4,5};for(autoit=v.begin();it!=v.end();++it){cout<<*it<<" ";}cout<<endl;// 配合范围forfor(autox:v){cout<<x<<" ";}cout<<endl;// 复杂类型map<string,vector<int>>m;auto&ref=m;// 引用// auto不能用于:// auto arr[10]; // ❌ 数组// auto func(); // ❌ 返回类型(需要尾置返回类型)return0;}

2. decltype

#include<iostream>usingnamespacestd;intmain(){intx=10;decltype(x)y=20;// y是intconstint&rx=x;decltype(rx)ry=x;// ry是const int&// 与auto的区别autoa=rx;// a是int(丢弃const和引用)decltype(rx)b=x;// b是const int&(保留)// 用于声明返回类型// auto add(int a, int b) -> decltype(a + b) {// return a + b;// }return0;}

3. nullptr

#include<iostream>usingnamespacestd;voidfunc(intn){cout<<"int: "<<n<<endl;}voidfunc(int*p){cout<<"int*"<<endl;}intmain(){// NULL是0,可能调用错误版本// func(NULL); // 可能调用func(int)func(nullptr);// 一定调用func(int*)int*p=nullptr;// 推荐用nullptrreturn0;}

4. 初始化列表

#include<iostream>#include<vector>#include<map>usingnamespacestd;classPoint{public:intx,y;Point(intx,inty):x(x),y(y){}};intmain(){// 统一初始化语法inta{10};intb={20};intarr[]{1,2,3,4,5};// 容器初始化vector<int>v={1,2,3,4,5};map<string,int>m={{"a",1},{"b",2}};// 类对象Point p{10,20};// 防止窄化转换// int n{3.14}; // ❌ 错误!double不能窄化为int// initializer_listautolist={1,2,3,4,5};// initializer_list<int>return0;}

5. 范围for循环

#include<iostream>#include<vector>#include<map>usingnamespacestd;intmain(){vector<int>v={1,2,3,4,5};// 只读遍历for(intx:v){cout<<x<<" ";}cout<<endl;// 修改元素for(int&x:v){x*=2;}// 避免拷贝(对于大对象)for(constauto&x:v){cout<<x<<" ";}cout<<endl;// 遍历mapmap<string,int>m={{"a",1},{"b",2}};for(constauto&[key,value]:m){// C++17结构化绑定cout<<key<<": "<<value<<endl;}return0;}

6. Lambda表达式

#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;intmain(){// 基本语法autoadd=[](inta,intb){returna+b;};cout<<add(3,5)<<endl;// 捕获变量intfactor=10;automultiply=[factor](intx){returnx*factor;};cout<<multiply(5)<<endl;// 引用捕获intsum=0;autoaddTo=[&sum](intx){sum+=x;};addTo(5);addTo(10);cout<<"sum = "<<sum<<endl;// mutable:允许修改值捕获的变量intcount=0;autocounter=[count]()mutable{return++count;};cout<<counter()<<endl;// 1cout<<counter()<<endl;// 2cout<<"count = "<<count<<endl;// 0(原变量不变)// 泛型Lambda (C++14)autoprint=[](autox){cout<<x<<endl;};print(10);print("hello");// 与STL配合vector<int>v={5,2,8,1,9};sort(v.begin(),v.end(),[](inta,intb){returna>b;// 降序});return0;}

7. 右值引用与移动语义

7.1 左值与右值

#include<iostream>usingnamespacestd;// 左值:有名字,可以取地址// 右值:临时值,不能取地址intmain(){inta=10;// a是左值,10是右值intb=a+5;// b是左值,a+5是右值// 左值引用int&ref1=a;// ✅// int& ref2 = 10; // ❌ 左值引用不能绑定右值// const左值引用可以绑定右值constint&ref3=10;// ✅// 右值引用int&&rref=10;// ✅ 右值引用绑定右值// int&& rref2 = a; // ❌ 不能绑定左值int&&rref3=move(a);// ✅ move将左值转为右值return0;}

7.2 移动语义

#include<iostream>#include<cstring>#include<utility>usingnamespacestd;classString{char*data;size_t len;public:// 构造函数String(constchar*s=""){len=strlen(s);data=newchar[len+1];strcpy(data,s);cout<<"构造: "<<data<<endl;}// 拷贝构造String(constString&other){len=other.len;data=newchar[len+1];strcpy(data,other.data);cout<<"拷贝构造: "<<data<<endl;}// 移动构造(窃取资源)String(String&&other)noexcept{data=other.data;len=other.len;other.data=nullptr;other.len=0;cout<<"移动构造: "<<data<<endl;}// 拷贝赋值String&operator=(constString&other){if(this!=&other){delete[]data;len=other.len;data=newchar[len+1];strcpy(data,other.data);}cout<<"拷贝赋值"<<endl;return*this;}// 移动赋值String&operator=(String&&other)noexcept{if(this!=&other){delete[]data;data=other.data;len=other.len;other.data=nullptr;other.len=0;}cout<<"移动赋值"<<endl;return*this;}~String(){delete[]data;}};intmain(){Strings1("Hello");String s2=s1;// 拷贝构造String s3=move(s1);// 移动构造(s1被掏空)Strings4("World");s4=String("Temp");// 移动赋值(临时对象)return0;}

8. constexpr

#include<iostream>usingnamespacestd;// 编译期常量constexprintsquare(intx){returnx*x;}constexprintfactorial(intn){returnn<=1?1:n*factorial(n-1);}intmain(){constexprinta=square(5);// 编译期计算constexprintb=factorial(5);intarr[square(3)];// ✅ 可以用于数组大小cout<<"5^2 = "<<a<<endl;cout<<"5! = "<<b<<endl;// 运行时也可以调用intx=4;cout<<square(x)<<endl;// 运行时计算return0;}

9. 其他特性

#include<iostream>usingnamespacestd;// 默认函数与删除函数classNonCopyable{public:NonCopyable()=default;// 使用编译器生成的默认版本NonCopyable(constNonCopyable&)=delete;// 禁止拷贝NonCopyable&operator=(constNonCopyable&)=delete;};// final和overrideclassBase{public:virtualvoidfunc(){cout<<"Base"<<endl;}virtualvoidfunc2()final{}// 不能被重写};classDerivedfinal:publicBase{// 不能被继承public:voidfunc()override{cout<<"Derived"<<endl;}// void func2() override {} // ❌ final不能重写};// 委托构造函数classPoint{intx,y;public:Point(intx,inty):x(x),y(y){}Point():Point(0,0){}// 委托给另一个构造函数Point(intv):Point(v,v){}};intmain(){return0;}

10. 小结

[类型推导] 1. auto - 自动推导类型 2. decltype - 获取表达式类型 [初始化] 3. 统一初始化 {} 4. 初始化列表 [函数] 5. Lambda表达式 6. constexpr函数 [移动语义] 7. 右值引用 && 8. move() 9. 移动构造/赋值 [类] 10. = default, = delete 11. final, override 12. 委托构造函数

下一篇预告:Day 18 - C++14/17新特性


版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/25 18:16:31

『NAS』告别付费和广告,在群晖部署PDF工具箱-bentopdf

点赞 关注 收藏 学会了 整理了一个NAS小专栏&#xff0c;有兴趣的工友可以关注一下 &#x1f449; 《NAS邪修》 BentoPDF 是一款隐私优先、纯浏览器端运行的 PDF 全能工具箱&#xff0c;可通过 Docker 轻松部署到 NAS。提供数十种处理 PDF 功能&#xff0c;所有文件处理均在…

作者头像 李华
网站建设 2026/4/24 14:18:38

基于深度学习YOLOv11的护目镜佩戴识别检测系统(YOLOv11+YOLO数据集+UI界面+登录注册界面+Python项目源码+模型)

一、项目介绍 本文设计并实现了一种基于深度学习YOLOv11的护目镜佩戴识别检测系统&#xff0c;旨在通过计算机视觉技术自动检测人员是否规范佩戴护目镜。系统采用YOLOv11目标检测算法&#xff0c;结合包含15,083张图像的自定义数据集&#xff08;训练集13,200张、验证集1,256张…

作者头像 李华
网站建设 2026/4/28 17:12:27

一键降AI工具推荐:2026年3分钟把AI率从90%降到10%

一键降AI工具推荐&#xff1a;2026年3分钟把AI率从90%降到10% 有没有一键搞定的降AI工具&#xff1f; 有。 这篇文章推荐几款真正的"一键降AI"工具&#xff0c;上传论文等几分钟&#xff0c;AI率就能从90%降到10%以下。 什么是"一键降AI"&#xff1f; …

作者头像 李华
网站建设 2026/4/18 15:57:37

知网AIGC检测升级!2026年还能用的免费降AI工具测评

知网AIGC检测升级&#xff01;2026年还能用的免费降AI工具测评 答辩前两周&#xff0c;我的论文被知网AIGC检测标红62%。 用了网上推荐的"免费降AI工具"&#xff0c;折腾了三天&#xff0c;AI率反而涨到了71%。后来才知道&#xff0c;知网在2025年12月底悄悄升级了…

作者头像 李华
网站建设 2026/4/23 4:56:30

零基础的初学者该怎么入门大语言模型(LLM)

随着人工智能技术的飞速发展&#xff0c;大模型已经成为推动这一领域进步的核心力量。它们通过处理海量数据&#xff0c;学习复杂的模式和关系&#xff0c;为各种应用提供了强大的智能支持。从语音识别到自动驾驶&#xff0c;再到个性化推荐系统&#xff0c;大模型正在不断地改…

作者头像 李华
网站建设 2026/3/31 15:25:51

P6015A 泰克Tektronix无源高压探头 40千伏

P6015A 泰克Tektronix无源高压探头 40千伏泰克P6015A高压探头 ‌是 泰克公司 研发的一款无源高压测量设备&#xff0c;主要用于电源设计、马达驱动器、 UPS系统 等场景的高压信号检测&#xff0c;适配数字示波器使用。其核心性能包括20kV直流电压与40kV峰值脉冲电压&#xff08…

作者头像 李华