c++之decltype和auto

1.auto

auto是当你不清楚某个变量类型时,让编译器来告诉你这个类型。

我们可以在范围for循环中看到。先看看下面的代码

#include<iostream>
using namespace std;
int main()
{
	int a = 10;
	auto b = a;//那么b的类型就是int
	const int c = 10;
	auto c1 = c;
	c1 = 50;//这是可以编译的,代表auto会自动忽略顶层const。
	const int *p = &a;
	auto p1 = p;
	p1 = 10;//这样时错误的,理解就是,auto会保存底层const,以便防止a的值被改变。
	auto &j = a;//引用
	auto &j1 = c;//虽然可以绑定但不能修改

	system("pause");
	return 0;
}

最后注意的一点是auto如果要声明为引用必须有&,如果要理解的话

就是一但一个变量是个引用,也就是它唯一绑定了另一个变量,是另一个

变量的另一个名字。

2.decltype

decltype 是c++11中新增的类型指示符。他的作用是选择并返回操作数的数据类型。看下面的代码

#include<iostream>
using namespace std;
int main()
{
	int a = 0;
	decltype(a) sum = 10;
	const int i = 10, &p = i;
	decltype(i) i1 = 15;
	decltype(i) i2 = i1;
	decltype(p) z;//大部分时候,引用都是另一个变量的名字。但这里是一个例外。
	//或者可以这样说,decltype保留了顶层const。
	int q = 10, *w = &q, &r = q;
	decltype(r + 0) r1 = 0;//加法的结果是int.
	decltype(*p) c ;//错误,因为解引用后的类型是int&.

	system("pause");
	return 0;
}

3typeid关键字

#include<iostream>
#include<typeinfo>
using namespace std;
int main()
{
	int a = 0;
	auto n = a;
	int *p = NULL;
	decltype(a) c = 5;
	decltype((a)) d = a;
	cout << typeid(a).name() << endl;
	cout << typeid(n).name() << endl;
	cout << typeid(c).name() << endl;
	cout << typeid(d).name ()<< endl;
	cout << typeid(p).name() << endl;


	system("pause");
	return 0;
}

 

可以试着尝试一下,注意引用.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值