2、auto 关键字

1、C 中的 auto

表示自动存储变量,临时申请一块变量内存地址,可以对比 static 关键字,staitc 静态存储,存储在全局数据区。

例如:

auto double x = 10.2;

表示 x 为一个自动存储的临时变量。

2、C++ 中的 auto

2.1 语法规则

auto 关键字实现 自动类型推导 功能,编译器会在编译期间自动推导出变量的类型,无需手动指明变量的数据类型,例如:

auto a = 10;    // a 为 int
auto b = 1.8;	// b 为 double
auto c = &a;    // c 为 int *
auto d = "china"; // d 为 const char *

int  x = 0;
auto *p1 = &x;   //p1 为 int *,auto 推导为 int
auto  p2 = &x;   //p2 为 int*,auto 推导为 int*
auto &r1  = x;   //r1 为 int&,auto 推导为 int
auto r2 = r1;    //r2 为  int,auto 推导为 int

int  x = 0;
const  auto n = x;  //n 为 const int ,auto 被推导为 int
auto f = n;      //f 为 const int,auto 被推导为 int(const 属性被抛弃)
const auto &r1 = x;  //r1 为 const int& 类型,auto 被推导为 int
auto &r2 = r1;  //r1 为 const int& 类型,auto 被推导为 const int 类型

2.2 常见应用

(1)定义迭代器

定义迭代器是最常见的用法。

#include <vector>
using namespace std;

int main(){
    vector< vector<int> > v;
    vector< vector<int> >::iterator i = v.begin();
    auto j = v.begin();  //使用 auto 代替具体的类型,相比上面实现,让编译器加班,更加简单
    vector<string> ll(10);
    //for (auto u : ll) {;}
	for (auto &u : ll) {;}    //使用引用方式,访问元素,效率更高
    return 0;
}
(2)泛型编程
#include <iostream>
using namespace std;
class A{
public:
    static int get(void){
        return 100;
    }
};
class B{
public:
    static const char* get(void){
        return "http://c.biancheng.net/cplus/";
    }
};
template <typename T>
void func(void){
    auto val = T::get();
    cout << val << endl;
}
int main(void){
    func<A>();
    func<B>();
    return 0;
}

不使用 auto 实现方案:

#include <iostream>
using namespace std;
class A{
public:
    static int get(void){
        return 100;
    }
};
class B{
public:
    static const char* get(void){
        return "http://c.biancheng.net/cplus/";
    }
};
template <typename T1, typename T2>  //额外增加一个模板参数 T2
void func(void){
    T2 val = T1::get();
    cout << val << endl;
}
int main(void){
    //调用时也要手动给模板参数赋值
    func<A, int>();
    func<B, const char*>();
    return 0;
}

参考:
http://c.biancheng.net/view/6984.html
https://baike.baidu.com/item/auto/10128?fr=aladdin#1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值