目录
一.auto关键字(C++11)
1.auto简介
2.作用:用于推导变量的类型
3. auto的使用细则
4.auto真正的意义
(1)类型很长时,懒得写,可以让他自动推导
(2)范围for
范围for的几个小细节:
5.auto不能推导的场景(以下全是错误示例)
(1)auto不能作为参数,缺省参数也不行
(2)auto不能定义时不初始化
(3)auto不能作返回值(为了防止滥用auto)
(4)auto不能直接用来声明数组(了解以下即可)
6.auto用法总结
二.NULL——0——nullptr 三者区分
1.NULL的详细解释:
2.nullptr详细解释
(2). 在同一行定义多个变量
void TestAuto()
{
auto a = 1, b = 2;
auto c = 3, d = 4.0; // 该行代码会编译失败,因为c和d的初始化表达式类型不同
}
下面的代码std::map
#include
using namespace std;
#include
概念:
用范围for打印数组
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
{
array[i] *= 2;
}
for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
{
cout << array[i] << " ";
}
cout << endl;
//上面是正常乘2打印数组,下面是范围for打印数组
// 范围for
// 依次自动取array中的数据,赋值给e,自动判断结束
for (auto e : array)
{
cout << e << " ";
}
cout << endl;
return 0;
}
如果用范围for改变数组内容需要加引用
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
{
array[i] *= 2;
}
for (int i = 0; i < sizeof(array) / sizeof(int); ++i)
{
cout << array[i] << " ";
}
cout << endl;
// 范围for
// 依次自动取array中的数据,赋值给e,自动判断结束
for (auto& e : array)
{
e/=2; //想要改变数组内的值,需要auto&,如果只用auto仅仅是拷贝
}
for (auto e : array)
{
cout << e << " ";
}
cout << endl;
return 0;
}
【1】e是单词元素element首字母,可以改成其他的字母表示
不一定只用auto,普通类型也可以,只是用了auto无论数组里什么类型都可以接收
(1)
for (auto& e : array)
{
e/=2; //e是单词元素element首字母,可以改成其他的字母表示
// x/=2; 也可以
}
(2)
//这里不一定只用auto,普通类型也可以,只是用了auto无论数组里什么类型都可以接收
for (int e : array)
{
e/=2;
}
【2】for循环迭代的范围必须是确定的
void TestFor(int array[])
{
for(auto& e : array)
cout<< e <
错误
此处代码编译失败,auto不能作为形参类型,因为编译器无法对a的实际类型进行推导
void TestAuto(auto a)
{}
错误
void TestAuto(auto a=10)
{}
错误!!
auto x;
错误
auto Test()
{
return 10;
}
错误
void TestAuto()
{
int a[] = {1,2,3};
auto b[] = {4,5,6};
}
最常用还是普通定义变量和范围for的使用
NULL,0,nullptr值都是0,但是类型不同,但是由于C头文件中NULL定义宏混乱,可能是int 0,也可能是(void*)0,所以我们在C++引入新的空指针nullptr,nullptr就是(void*)0,所以我们在C++中空指针统一用nullptr
可以看到,NULL可能被定义为字面常量0,或者被定义为无类型指针(void*)的常量。不论采取何种定义,在 使用空值的指针时,都不可避免的会遇到一些麻烦
利用函数重载证明NULL和0是是整形0,nullptr是(void*)0:
void f(int) {
cout << "f(int)" << endl;
}
void f(int*) {
cout << "f(int*)" << endl;
}
int main()
{
f(0); //调用了void f(int)
f(NULL); //调用了void f(int)
f(nullptr); //调用了void f(int*)
return 0;
}