C++新特性学习
委托构造函数
c++11
class Test {
public:
Test(int n) {}
Test() :Test(0) {}
};
可以避免在不同的构造函数中重复编写相似的初始化代码,提高了代码的可维护性和可读性
初始化列表
struct Data {
int i = 1;
float f = 2.0;
bool b = true;
};
空指针
int main(){
char *s = NULL;//别用了
char *s = nullptr;
}
枚举类
enum class Color {
Red,
Green,
Blue
};
int main() {
Color c = Color::Red;
if (c == Color::Red) {
}
return 0;
}
enum 强类型 无法进行隐式转换
类型推导auto
对于各种数据类型,迭代器等可直接用auto进行类型推导
//迭代器
for (auto it = s.begin(); it != s.end(); it++) {
cout << *it << ' ';
//数据类型
auto a = 1;
//函数的返回值
auto add(int x,int y){
return x + y;
}
常量表达式constexpr
将运行时的计算提前到编译时来计算进行优化
可修饰变量,函数等等
constexpr int size = 10;
constexpr int square(int x) {
return x * x;
}
初始化列表
类似于普通数组的创建
vector<int>a = { 1,2,3,4,5 };
map<int, int>a = { {1,1},{2,3},{3,5} };
基于范围的for循环
一种新的元素遍历
原本的方式
vector<int>v = { 1,2,3 };
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it;
}
新的遍历方式
vector<int>v = { 1,2,3 };
for (int c : v) {
cout << c << endl; //..不需要解引用
}
vector<string>ve = { "早上","好","中国" };
for (string b : ve) {
cout << b;
}
map<int, int>map = { {1,1},{2,3},{3,5} };
for (auto a : map) {
cout << a.first << "->" << a.second << endl;
}
C++17可以使用
map<int,string>m = { {1,"早上好"},{2,"你好"},{3,"晚上好"}};
for (auto [key,val] : m) {
cout << key << "->" << val << endl;
}
智能指针
所需要的头文件 #include<memory>
#include<iostream>
#include<memory>
using namespace std;
struct SomeDate {
int a, b, c;
};
void f() {
//常规写法
//SomeDate* date = new SomeDate;
//unique_ptr<SomeDate> date(new SomeDate);
//推荐写法
auto date = make_unique<SomeDate>();
date->a = 1;
date->b = 2;
date->c = 3;
}
make_unique指向对象唯一的智能指针
需要指针在不同函数间传递,或者多个指针指向同一个对象则使用shared_ptr
Lanbda表达式
int main() {
vector<int>a = { 1,2,3,4,5 };
auto it = find_if(a.begin(), a.end(), [](int x) {return x > 3; });
cout << *it;
}