天天看点

C++ 的自动类型auto类型推断decltype空指针nullptr 快速遍历for inauto 自动类型decltype 推断表达式的类型nullptr 空指针,专门针对指针做的符号for in快速遍历 ,语法格式是for (😃

目录

  • auto 自动类型
  • decltype 推断表达式的类型
  • nullptr 空指针,专门针对指针做的符号
  • for in快速遍历 ,语法格式是for (:)

C++ 11以后的一下新语法常用的如下:

auto 自动类型

这个相当于swift里面的var ,自动通过右边表达式推断出类型.

示例代码如下:

auto a = 5;//自动把a推断为 int类型
a = 6.14;
cout<< a <<endl; //输出6,因为a 是int类型
auto d = 3.14;//把d当成double,相当于double d = 3.14
d = 5;
cout << d <<endl;//输出5,把d当成double
           

decltype 推断表达式的类型

这个跟typeof作用一样.decltype,推断后面表达式的类型,返回类型

int a2 = 3;
double d2 = 3.14;
decltype(a2) c = 5;//推断a2的类型为int,然后用int 定义 c,相当于 int c = 5
cout << c <<endl;
decltype(a2+d2) c2 = 5.11;//推断出a2+d2 = 3+ 3.14 =6.14 是浮点型.然后用浮点型定义5.11 ,相当于是double c2 = 5.11
cout <<sizeof(c2)<<endl;
cout <<sizeof(double)<<endl;//c2和double的长度都是8,说明是double不是float
cout << c2 <<endl;
/*
 typeof也是推断表达式类型,返回类型,和decltype作用一样
 */
typeof (a2+d2)c3 = 6.11;
cout <<c3 <<endl;
           

nullptr 空指针,专门针对指针做的符号

因为NULL是0 ,可以用来给指针赋值,当有函数接收空指针的时候,和接收int的时候会产生二义性.用nullptr,就是直接调用指针参数的函数.

下面例子2个函数test都接收参数分别是 int和 int* ,用了nullptr就是直接调用int* ,如果传入NULL就会产生二义性,编译器不知道调用哪个

void test(int a){
      cout<<"test(int a)"<<endl;
}
void test(int *p){
      cout<<"test(int *p)"<<endl;
}
int main(int argc, const char * argv[]) {
//      test(NULL);//xcode下编译会报错,模糊不清
      test(nullptr);
}
           

for in快速遍历 ,语法格式是for (😃

c++的快速遍历,语法是 for : ,相当于 其他语言的swift的for in

int arr[] = {1,2,3,4,5};
for(int item:arr){
      cout<<item<<endl; //item是每次遍历数组里的arr[i]
}
           

继续阅读