找回密码
 立即注册
首页 业界区 业界 自动类型推导

自动类型推导

猷浮 5 天前
c++11中添加了自动推导变量的类型auto,以及decltype表示函数的返回值。
auto

auto可以像别的语言一样自动推导出变量的实际类型。
在实际中,auto像是一个”占位符“,使用auto声明的变量必须要进行初始化,以让编译器推导出它的实际类型,在编译时将auto换成真正的类型。
语法:
  1. auto 变量名 = 变量值
复制代码
实际使用例子:
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4.         //没有const修饰
  5.         auto x = 3.14; //double
  6.         auto y = 520;  //int
  7.         auto z = 'a';  //char
  8.         //auto nb;       //语法错误
  9.         //auto double nbl; //语法错误
  10.         int temp = 110;
  11.         auto* a = &temp; //&temp:int*   auto*:int*     auto:int
  12.         auto b = &temp;  //auto:int*
  13.         auto& c = temp;  //auto:int
  14.         auto d = temp;   //auto:int
  15.         //有const修饰
  16.         int tmp = 250;
  17.         const auto a1 = tmp;  //auto:int   a1:const int
  18.         auto a2 = a1;         //a1不是指针也不是引用       auto:int        a2:int
  19.         const auto& a3 = tmp; //a3:const int&      auto:int
  20.         auto& a4 = a3;        //a3是引用类型       a3:const int&     a4:const int&    auto&:const int&   auto:const int
  21.         auto* pt4 = &a1;      //&a1是地址     a1:const int   pt4:const int*    auto:const int
  22.         system("pause");
  23.         return 0;
  24. }
复制代码
需要注意的是:
在auto和指针、引用结合在一起时,推导的结果会保留const、volatile关键字(volatile表示变量,经常修改的变量)

  • 当变量不是指针或者引用类型时,推导的结果中不会保留const、volatile关键字。
  • 当变量时指针或者引用类型时,推导的结果中会保留const、volatile关键字。
就如上述代码中的   //有const修饰  后面的代码,需要注意变量是否为指针或者引用类型。
auto不能推导的4个情况

1. 不能作为函数参数使用,因为只有在函数调用的时候才会给函数参数传递实参,auto要求必须要给修饰的变量赋值,因此二者不矛盾。

[code]int func(auto a, auto b) {  //error        cout

相关推荐

您需要登录后才可以回帖 登录 | 立即注册