news 2026/3/8 7:02:55

【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/2/27 4:23:13

【30天精通汇编】Day 1: 计算机基础与二进制

【30天精通汇编】Day 1: 计算机基础与二进制&#x1f4c5; 学习时间&#xff1a;3-4小时 &#x1f3af; 学习目标&#xff1a;理解计算机底层原理&#xff0c;掌握二进制运算 &#x1f4a1; 难度&#xff1a;★☆☆☆☆ &#x1f4cb; 前置要求&#xff1a;零基础可学&#x1f…

作者头像 李华
网站建设 2026/3/7 16:51:19

探秘《Hands on Large Language Models》:开启大模型学习之旅(附教程)

今天要给大家介绍一本在大语言模型领域超有分量的新书 ——《Hands on Large Language Models》。目前已经正式发布&#xff0c;干货满满&#xff0c;绝对能让你抢先一步深入大语言模型的奇妙世界。 当大语言模型遇上 “实战指南” 这几年&#xff0c;大语言模型那可是火得一塌…

作者头像 李华
网站建设 2026/2/24 2:16:57

降AI工具安全吗?论文会被收录吗?2026年隐私保护指南

降AI工具安全吗&#xff1f;论文会被收录吗&#xff1f;2026年隐私保护指南 用降AI工具处理论文&#xff0c;安全吗&#xff1f;会不会被收录到数据库&#xff1f; 这是很多同学担心的问题。毕竟论文是自己的心血&#xff0c;万一被泄露或收录就麻烦了。 这篇文章帮你搞清楚…

作者头像 李华
网站建设 2026/2/27 4:23:13

下载与快速上手 NVM:Node.js 版本管理工具

一、准备工作&#xff1a;卸载旧版 Node.js 重要提示&#xff1a;在安装 NVM 前&#xff0c;请先彻底删除已安装的 Node.js&#xff0c;避免路径冲突&#xff1a;检查安装路径where node常见路径&#xff1a;C:\Program Files\nodejs\ C:\Users\用户名\AppData\Local\nodejs\卸…

作者头像 李华
网站建设 2026/3/1 22:57:41

2026年最新降AI攻略总结:一站搞定论文AIGC检测

2026年最新降AI攻略总结&#xff1a;一站搞定论文AIGC检测 这篇文章是2026年降AI攻略的终极总结。 如果你只想看结论&#xff0c;直接拉到最后。如果想了解细节&#xff0c;继续往下看。 2026年AIGC检测现状 检测平台&#xff1a;知网、维普、万方 红线标准&#xff1a; 本…

作者头像 李华
网站建设 2026/3/5 6:49:30

DeepSeek+豆包+Kimi降AI指令有用吗?2026年实测告诉你真相

DeepSeek豆包Kimi降AI指令有用吗&#xff1f;2026年实测告诉你真相 网上流传着很多"降AI指令"&#xff0c;说用DeepSeek、豆包、Kimi就能把AI率降下来。 我认真测试了一下&#xff0c;结论是&#xff1a;有一定效果&#xff0c;但很有限。 想把AI率从60%降到10%以…

作者头像 李华