c++中的auto关键字

auto的属性特征

#include <iostream>
using namespace std;

int main() {
	//1.auto 变量必须在定义时初始化,类似于const
	auto i1 = 0; auto i2 = i1;
	//auto i3; //错误,必须初始化
	//2.如果初始化表达式是引用,则去除引用语义
	int a1 = 10;
	int &a2 = a1; // a2是引用
	auto a3 = a2; // a3是int类型,而不是引用
	auto &a4 = a1; // a4是 引用
	//3.去除顶层const
	const int b1 = 100;
	auto b2 = b1; // b2 是 int
	const auto b3 = b1; // b3是 const int
	//4.带上底层const
	auto &b4 = b1; // b4 是 const int 的引用
	//5.初始化表达式为数组时,推导类型为指针
	int arr[3] = { 1,2,3 };
	auto parr = arr; //parr 是 int * 类型
	cout << typeid(parr).name() << endl;
	//6.表达式为数组且auto带上&,推导类型为数组
	auto &rarr = arr; //rarr 是 int [3]
	cout << typeid(rarr).name() << endl;
	//7.函数参数类型不能是 auto
	//func(auto arg); //错误
	//8.auto并不是一个真正的类型,编译时确定
	//sizeof(auto); 错误
	return 0;
}

auto使用实例

auto推导的一个最大的优势在于拥有初始化表达式的复杂类型变量声明时简化代码

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
	vector<string> vs =
		{ "all","people","like","c++" };

	for (vector<string>::iterator i = 
			     vs.begin(); i != vs.end(); i++)
		cout << *i << " ";
	cout << endl;

	for (auto i = vs.begin(); i != vs.end(); i++) 
		cout << *i << " ";
	cout << endl;

	for (auto &s : vs)
		cout << s << " ";
	cout << endl;

	return 0;
}

auto的详细参考

auto详细解释

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值