C++(11):auto通过初始化类型推导变量类型

325 篇文章 3 订阅 ¥299.90 ¥399.90
本文介绍了C++11中auto关键字的使用,它能简化复杂类型变量的定义,但要求变量必须初始化。同时,auto不适用于函数形参,但在C++14中可用于lambda函数的形参声明。auto的推导规则遵循模板参数推导,但也存在特殊情况。
摘要由CSDN通过智能技术生成

C++11赋予了auto新的含义,可以通过auto自动推导变量的类型:

#include <iostream>
using namespace std;

int main(){
	auto i = 1;
	cout<<"type of i is:"<<typeid(i).name()<<endl;
	auto m = 3.14;
	cout<<"type of m is:"<<typeid(m).name()<<endl;
	auto n = &i;
	cout<<"type of n is:"<<typeid(n).name()<<endl;
	auto k = i;
	cout<<"type of k is:"<<typeid(k).name()<<endl;
	auto l = "hello word";
	cout<<"type of l is:"<<typeid(l).name()<<endl;
	return 0;
}

运行程序输出:
type of i is:i
type of m is:d
type of n is:Pi
type of k is:i
type of l is:PKc

auto可以简化复杂类型的变量定义:

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

int main(){
	vector<int> a = {1, 2, 3, 4};
	for(auto i = a.begin(); i < a.end(); i&
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风静如云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值