【C++11新特性自动类型推导auto】

auto:

声明的变量要进行初始化

1普通变量

auto a=10;  //就是根据后面的值->推导前面的定义
cout<<typeid(a).name()<<endl; //通过typeid获得对象a的类型   输出int

2引用和指针

auto a=10;
auto b=&a;  //int *    等价于:auto *b我认为这么做的目的是好区分
auto c=&b;  //int **   等价:同上

auto& c=a;  //int& 

3const修饰

重点:当变量不是指针和引用,auto不会保留const和volatile关键字,反之即可

	int a = 10;
	const auto b = a;  //const int
	auto c = b;    //int
	auto& d = b;   //const int&
	auto e = &b;   //const int*

这两行代码自己理解一下    不懂:const专题

	const int* const e = &a; 
	*e = 100; e = &x;   //全err
	const int const* f = &a;
	*f = 1000; f = &x;  //后err

4auto二义性

auto a = 10, b = 1.3;  //err

不能用auto的场景

1函数形参:因为auto必须给变量赋值,相矛盾

2非常量静态成员

class A {
public:
	//auto a = 0;               //err
	//static auto b = 1;        //err  在我们类中静态成员变量要在全局区::方式初始化
	const static auto c = 1;    //Yes

};

3数组

	int arr[] = {1,2,3,4,5};
	auto a = arr;               //ok  auto:int*
	//auto arr[] = arr;         //err 
	//auto arr[10] = {};        //err

4模板

template <class T>
class person{};

void f()
{
person<int> a;
person<auto> b; //err

}

auto方便之处

1STL 容器遍历

	//很繁琐
    vector<int>v = { 1,2,3,4,5,6,7,8,9 };
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
		cout << *it;
	//new
	for (auto it : v)
		cout << it;

2泛型编程

#include<iostream>
using namespace std;

class A {
public:
	static string show()
	{
		return "hello future";
	}
};

class B {
public:
	static int show()
	{
		return 123;
	}
};

template<class T>
void f()
{
	auto i = T::show();
	cout << i << endl;
}

int main()
{
	f<A>();
	f<B>();
	return 0;
}

  • 14
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值