C++11之 auto

C++11类型推导

1、使用auto的时候,编译器根据上下文情况,确定auto变量的真正类型。auto在C++14中可以作为函数的返回值,因此auto AddTest(int a, int b)的定义是没问题的。

auto AddTest(int a, int b) 
{
    return a + b;
}

int main()
{
    auto index = 10;
    auto str = "abc";
    auto ret = AddTest(1,2);
    std::cout << "index:" << index << std::endl;
    std::cout << "str:" << str << std::endl;
    std::cout << "res:" << ret << std::endl;
}

2、只能用于定义函数,不能用于声明函数。

#pragma once
class Test
{
public:
    auto TestWork(int a ,int b);
};

   但如果把实现写在头文件中,可以编译通过,因为编译器可以根据函数实现的返回值确定auto的真实类型。

#pragma once
class Test
{
public:
    auto TestWork(int a, int b)
    {
        return a + b;
    }
};

3、

  auto 关键字。这会依据该初始化子(initializer)的具体类型产生参数:

  

  除此之外,decltype 能够被用来在编译期决定一个表示式的类型。

  

参考:

1、https://www.cnblogs.com/feng-sc/p/5710724.html

2、

  

原文地址:https://www.cnblogs.com/tekkaman/p/3500485.html