C++11新特性
2021/5/1 14:25:34
本文主要是介绍C++11新特性,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、原生字符串(raw string literals)
比如我们写硬盘上一个文件的访问路径:"C:\Program Files\Microsoft.NET\ADOMD.NET",你需要把它写成以下格式
string path = "C:\\Program Files\\Microsoft.NET\\ADOMD.NET";
这样取消字符串转义太麻烦了,C++11下可以这样写:
string path = R"(C:\Program Files\Microsoft.NET\ADOMD.NET)";
除了上面这样,你还可以使用引号
string path = R"(this "word" is good)";
二、委托构造函数(Delegating constructors)
说简单一点就是你的一个构造函数可以调用另一个构造函数
#include <bits/stdc++.h> using namespace std; multimap<int, int> r; multimap<int, int>::iterator it; class people { public: string name; int age; int id; people(int age,int id):age(age),id(id) { } //委托构造函数不能具有其他成员初始化表达式 // people(int age,int id,string name):name(name),people(age,id) // { // } people(int age,int id,string name):people(age,id) { } }
三、初始化列表
用列表的形式来初始化数组,这种方式非常直观,但只能适用于数组,不能适用于我们自定义的容器:
int anArray[5] = { 3, 2, 7, 5, 8 }; // ok
std::vector<int> vArray = { 3, 2, 7, 5, 8 }; // 不支持
C++11现在支持了
#include <bits/stdc++.h> using namespace std; template<typename T> class test{ private: vector<T> arr; public: test(){} test(const initializer_list<T>& li){ for(auto x : li){ arr.push_back(x); } } }; class Value{ public: int x,y; double z; Value(int a,int b,double c):x(a),y(b),z(c){ } }; int main(){ test<int> t={1,2,3,4}; return 0; }
四、统一初始化
C++对象初始化方法有很多种,C++ 11中,允许通过以花括号的形式来调用构造函数。这样多种对象构造方式便可以统一起来了
#include <bits/stdc++.h> using namespace std; multimap<int, int> r; multimap<int, int>::iterator it; class Value{ public: int x,y; double z; //不加这个构造函数也不会报错,但是为了看起来清晰建议还是加上 Value(int a,int b,double c):x(a),y(b),z(c){ } }; Value te(){ return {1,2,0.1}; } int main(){ Value v = te(); printf("%d %d %lf\n",v.x,v.y,v.z); return 0; }
#include <bits/stdc++.h> using namespace std; multimap<int, int> r; multimap<int, int>::iterator it; int main() { r.insert({1,2}); r.insert({1,3}); for(it=r.begin();it!=r.end();it++){ printf("%d %d\n",it->first,it->second); //std:cout << it->first << " is " << it->second << std::endl; } return 0; }
这篇关于C++11新特性的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28pyqt 怎么打包整个项目-icode9专业技术文章分享
- 2024-09-28laravel Commands 创建带有参数的 Artisan 命令的步骤和示例-icode9专业技术文章分享
- 2024-09-28antd怎么实现渲染tiff图片-icode9专业技术文章分享
- 2024-09-28英文半角中划线和中文全角的中划线有什么区别-icode9专业技术文章分享
- 2024-09-28nvm npm 和node 他们之间有什么关系-icode9专业技术文章分享
- 2024-09-28Node Version Manager (nvm)使用教程-icode9专业技术文章分享
- 2024-09-28nvm命令太慢,是什么原因-icode9专业技术文章分享
- 2024-09-28Kotlin 如何增加、删除和修改 MutableStateFlow 中的值。-icode9专业技术文章分享
- 2024-09-28Kotlin的stateFlow.update 写法介绍-icode9专业技术文章分享
- 2024-09-28kotlin 怎么获取当前时间格式-icode9专业技术文章分享