C++入门(4):auto、范围for、nullptr

一、关键词 auto

1.1 概念

auto 作为一个新的类型指示符 来指示编译器,auto 声明的变量必须由编译器在编译时期推导而得。

cpp 复制代码
#include <iostream>
using namespace std;

int main()
{
    int a = 0;
    
    auto b = a;
    auto c = &a;
    auto* d = &a;
    auto& e = a;
    
    cout << typeid(b).name() << endl;
    cout << typeid(c).name() << endl;
    cout << typeid(d).name() << endl;
    cout << typeid(e).name() << endl;
    
    return 0;
}

PS:

  1. 使用 auto 定义变量时,必须对其初始化。在编译阶段,编译器根据初始化表达式推导 auto 的实际类型。
  2. auto 并非一种类型声明,而是一种类型声明时的**"占位符"**,编译器在编译阶段会将 auto 替换为变量的实际类型。
1.2 使用
  1. 在声明指针时,auto 与 auto * 没有实际区别;在声明引用时,必须使用 auto&
cpp 复制代码
int main()
{ 	
    int a = 0;
    
    auto c = &a;
    auto* d = &a;
    auto& e = a;
    
    return 0;
}
  1. 同一行 定义多个变量时,变量类型必须相同,否则编译器会报错。
cpp 复制代码
int main()
{
    auto a = 10, b = 2.2;// error C3538: 在声明符列表中,"auto"必须始终推导为同一类型
    return 0;
}
  1. auto 不能用来声明数组
cpp 复制代码
int main()
{
    auto a[4] = {1, 2, 3, 4};// error C3318: "auto []": 数组不能具有其中包含"auto"的元素类型
    return 0;
}
  1. auto 不能用来做函数参数类型
cpp 复制代码
void f(auto) // error C3533: 参数不能为包含"auto"的类型
{
    // ...
}
int main()
{
    f(0);
    return 0;
}

二、基于范围的for循环

2.1
cpp 复制代码
#include <iostream>
using namespace std;

int main()
{
	int array[] = { 1, 2, 3, 4, 5 };
	for (auto e : array)
		cout << e << " ";

	return 0;
}

PS:

与普通for循环相同,可以使用continue 结束本次循环,使用break结束整个循环。

2.2 范围for的使用条件
  1. for循环的迭代范围必须是确定的
cpp 复制代码
void Func(int arr[]) // error:arr数组的范围不确定
{
    for (auto e : arr)
        cout << e << " ";
}

三、指针空值nullptr

观察以下程序:

cpp 复制代码
void f(int)
{
    cout << "f(int)" << endl;
}

void f(int*)
{
    cout << "f(int*)" << endl;
}

int main()
{
    f(0);
    f(NULL);
    return 0;
}

NULL实际是个宏,在<corecrt.h>文件中,可以看到:

cpp 复制代码
#ifndef NULL
    #ifdef __cplusplus
        #define NULL 0
    #else
        #define NULL ((void *)0)
    #endif
#endif

C++11 中引入新关键词 nullptr 表示指针空值,使用时不需要包含头文件。

sizeof(nullptr) 与 *sizeof((void)0)** 所占字节数相同,后续表示指针空值时最好使用 nullptr。

相关推荐
平常心的技术小牛17 分钟前
Qt-快速上手-QLabel
开发语言·qt
呜喵王阿尔萨斯19 分钟前
C/C++ 杂记-1
c++
XR12345678820 分钟前
工厂办公楼无线网络:多楼层覆盖与访客体验怎么选?
开发语言·php
JL1521 分钟前
Java并发编程面试全攻略-从synchronized到AQS底层原理
java·开发语言·面试·并发编程
云泽80822 分钟前
Python 开发环境搭建全指南:从 Python 安装到 PyCharm 配置详解
开发语言·python·pycharm
不会代码的小猴29 分钟前
2. 了解Qt
开发语言·c++·笔记·qt·算法
ZJU_统一阿萨姆31 分钟前
【推理优化进阶】Hopper_Blackwell 微架构:从指令、流水线到真实性能上限
开发语言·人工智能·语言模型·架构·开源
兵哥工控43 分钟前
mfc实现在数值范围内实时改变静态文本控件字体颜色实例
c++·mfc
程序喵大人3 小时前
【C++进阶】STL算法与函数对象 - 09 函数对象保存状态并复用规则
开发语言·c++·算法·stl·函数对象
ShineWinsu8 小时前
对于C++:auto_ptr、unique_ptr、shared_ptr的模拟实现
c++·面试·笔试·智能指针·unique_ptr·shared_ptr·auto_ptr