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。

相关推荐
xiaoye-duck6 小时前
吃透C++类和对象(中):拷贝构造函数的深度解析
c++
kaikaile19956 小时前
雷达仿真中时域与频域脉冲压缩的对比 MATLAB实现
开发语言·matlab
胡闹546 小时前
【EasyExcel】字段赋值错乱问题
java·开发语言
独自归家的兔6 小时前
基于GUI-PLUS 搭配 Java Robot 实现智能桌面操控
java·开发语言·人工智能
ew452186 小时前
【JAVA】实现word的DOCX/DOC文档内容替换、套打、支持表格内容替换。
java·开发语言·word
企微自动化6 小时前
企业微信外部群自动化系统的异常处理机制设计
开发语言·python
墨&白.6 小时前
如何卸载/更新Mac上的R版本
开发语言·macos·r语言
技术小甜甜6 小时前
[Python] 使用 Tesseract 实现 OCR 文字识别全流程指南
开发语言·python·ocr·实用工具
leo__5206 小时前
MATLAB 实现 基分类器为决策树的 AdaBoost
开发语言·决策树·matlab
老朱佩琪!6 小时前
Unity原型模式
开发语言·经验分享·unity·设计模式·原型模式