0
点赞
收藏
分享

微信扫一扫

[C++笔记]C++11中的auto,范围for,以及nullptr

夕阳孤草 2022-02-20 阅读 29
c++
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

//auto关键字(C++11)
void AutoTest1() {
	//废弃了早期C的用法:
	//auto int a=0;//int a已经是默认存储类型,早期auto的意义被架空
	const int a = 0;
	//现改为:
	auto b = a;//自动根据右边的值推导左边的类型,a是什么类型b就是什么类型
	auto m = &a;
	auto c = 'A';
	auto d = 114.514;
	
//用typeid().name()打印变量类型
	cout << typeid(a).name() << endl;
	cout << typeid(b).name() << endl;//注意,auto推类型时会不管const属性
	cout << typeid(m).name() << endl;
	cout << typeid(c).name() << endl;
	cout << typeid(d).name() << endl;
	cout << endl;
}

//用auto声明指针类型时,用auto和auto*没区别,但用auto声明引用类型时则必须加&
void AutoTest2() {
	int x = 10;
	auto a = &x;//int*
	auto* b = &x;//int*
	auto& c = x;//int
	cout << typeid(a).name() << endl;
	cout << typeid(b).name() << endl;
	cout << typeid(c).name() << endl;
	*a = 20;
	*b = 30;
	c = 40;
	cout << endl;
}
//*auto不能用于作参数和声明数组,因编译器无法推导实际类型

//auto的实际应用方式:
//std::map<std::string,std::string> dict ={{"sort","排序"}{"insert","插入"}};
//std::map<std::string,std::string>::iterator it = dict.begin();
//把上面的直接改成:
//auto it=dict.begin();//简化操作

//auto的另一个好用处:一个语法糖--范围for
void TestFor(int a[]) {
	int array[] = { 1, 2, 3, 4, 5 };
	// C/C++ 遍历数组
	for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
	{
		cout << array[i] << endl;
	}
	// C++11 范围for
	// 自动依次取数组array中的每个元素赋值给e并自动判断结束
	for (auto x : array){//不使用auto而手动写出类型,也叫范围for,用auto更方便且利于维护
		cout << x << endl;
	}
	for (auto& x : array) {//这里x和一般循环里的循环变量i生命周期不同,只针对当下的一次循环
		x++;//每个元素+1
	}
	//范围for的范围必须是确定的(数组范围就是首尾元素,而对于类应提供begin和end的方法)
	//如范围for数组,范围必须用数组名,而如int数组传参时会退化成int*,不再是数组名,begin和end不确定,范围不确定
	//在底层,范围for的汇编代码跟普通for其实一样
}

//C++11中的指针置空:nullptr
void NullPointer(){
	//C++98/03
	int* p1 = NULL;
	int* p2 = 0;
	//NULL是宏定义的,预处理后替换为0,极端场景下用NULL会有问题:
	//比如,对于重载函数f(int)与f(int*),f(NULL)和f(0)都当作传了int处理
	//重载函数传NULL不能区分指针与整型,因此C++11起不再推荐用NULL

	//C++11
	int* p3 = nullptr;
	//nullpt作为关键字不需要包头文件,可以区分int* 0与int 0
	//在C++11中,sizeof(nullptr)==sizeof((void*)0)为真
}

int main() {
	AutoTest1();
	AutoTest2();
	int arr[] = { 1,2,3,4,5 };
	TestFor(arr);
	return 0;
}
举报

相关推荐

0 条评论