C++11基础-----Auto关键字及注意点

1.使用阿里云服务器,选择的centos版本,首先安装g++ 4.8.5

yum install gcc-c++

2.写个小程序测试一下:

#include "iostream"

using namespace std;

int main()
{
    auto a = 1;
    return 0;

}

编译报错,找不到auto这种类型

3.auto的限制

  • auto不能用于函数参数
void testFunc(auto iParam)
{

}
test.cpp:5:20: error: parameter declared ‘autovoid testFunc(auto iParam)                    ^
  • auto不能用于非静态成员变量
struct Foo
{
    auto var1_ = 0;
    static const auto var2_ = 0;
};
test.cpp:12:15: error: non-static data member declared ‘autoauto var1_ = 0;               ^
  • auto仅能用于推导static const的整型或者枚举成员。
    1. auto无法定义数组
    2. auto无法推导出模板参数
    3. 列表内容

4.什么时候用auto

  • 优化代码美观性,减少冗余和繁琐的重复操作
int main()
{
    auto a = 1;

    std::unordered_multimap<int, int> resultMap;
    //...
    std::pair<std::unordered_multimap<int, int>::iterator,
        std::unordered_multimap<int, int>::iterator> 
            range = resultMap.equal_range(key);

    return 0;

}

=>

int main()
{
    auto a = 1;

    std::unordered_multimap<int, int> resultMap;
    //...
    auto range = resultMap.equal_range(key);

    return 0;

}
  • 无法提前感知函数返回类型的时候
class Foo
{
public:
    static int get(void) 
    //...
}

class Bar
{
public:
    static const char* get(void)
    //...
}

template <class A>
void func()
{
    auto val = A::get();
}

参考文献:
《深入应用C++11》

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值