版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012581760/article/details/87879377
1 auto
可以从初始化表达式中推断出变量的类型,大大简化编程工作
属于编译器特性,不影响最总的机器码质量,不影响运行效率
2 decltype
可以获取变量的类型 int a = 10; decltype(a) b = 20;// int
3 nullptr
可以解决NULL的二义性问题,是null pointer空指针
4 快速遍历特性
5 更加简洁的初始化方式
6 Lambda表达式:有点类似于JavaScript中的闭包,iOS中的Block,本质就是函数
它的完整结构:[capture list] (params list) mutable exception -> return type {function body}
capture list:捕获外部变量列表
params list:形参列表,不能使用默认参数,不能省略参数名
mutable:用来说是否可以修改捕获的变量
exception:异常设定
return type:返回值类型
function body:函数体
有时可以省略部分结构
[capture list] (params list) -> return type {function body}
[capture list] (params list) {function body}
[capture list] {function body}
class Person {
public:
int m_age;
};
void func(int p){
cout << "func (int)"<< endl;
}
void func(int *p){
cout << "func (int *)"<< endl;
}
int sum(int a,int b) {return a + b;}
int mins1(int a, int b) {return a - b;}
int multiple(int a, int b) {return a * b;}
int divide(int a, int b) {return a / b;}
int exex(int a,int b, int (*func(int, int)) {
return func(a,b);
}
int main(){
auto c = 10;
auto d = "jack";
auto p = new Person();
p -> m_age = 10;
// 编译器可以直接识别出来类型
func(NULL);// 调用的是func(int)
func(nullptr);// 调用的是func(int *)
// 快速遍历特性
int array[] = {10,20,30,40};
for (int item:array) {
cout << item << endl;
}
// 更加简洁的初始化方式
int array1[] {11,22,33,44};
// 定义了一个局部函数
[] (int a, int b) -> int {
return a + b;
};
// 指向函数类型的指针
int (*p)(int,int) = [] (int a, int b) -> int {
return a + b;
};
p(10,20);
// [] (int a, int b) -> int {
return a + b;
}(10,20);
cout << exec(20, 10, sum) << endl;
cout << minus1(20, 10, sum) << endl;
cout << multiple(20, 10, sum) << endl;
cout << divide(20, 10, sum) << endl;
cout << exec(20, 10, [](int a, int b) {return a + b;}) << endl;
cout << exec(20, 10, [](int a, int b) {return a - b;}) << endl;
cout << exec(20, 10, [](int a, int b) {return a * b;}) << endl;
cout << exec(20, 10, [](int a, int b) {return a / b;}) << endl;
int a = 10;
int b = 20;
// 外部变量捕获,将外面的参数捕获到内部,默认情况下是值捕获.
[a, b]{
cout << a << endl;
cout << b << endl;
}();
// 捕获的是外部变量的地址用的引用.
auto f = [&a, b] {
cout << a << endl;
cout << b << endl;
};
a = 11;
b = 20;
f();
// mutable 在内部自己搞一个变量
auto p1 = [a] () mutable {
a++;
cout << "lambda - "<< a << endl;
};
p1();
cout << a << endl;
getchar();
return 0;
}