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;
}

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

猜你喜欢

转载自blog.csdn.net/qq_43702629/article/details/88870803