【auto关键字笔记】

本文介绍了C++中的`auto`关键字,用于变量声明时的类型推断和函数返回值占位。通过示例展示了如何使用`auto`声明变量、模板函数以及注意事项,包括`auto`不能用于函数参数和模板参数,不推导顶层const,以及数组类型的特殊处理。同时强调了`auto`在指针和引用类型修饰下的行为。
摘要由CSDN通过智能技术生成

auto关键字笔记

在力扣的题解中看到auto关键字,之前并没有接触过,了解了一下并把可能会经常用的用法记了个笔记

原文在这里

用法:

  1. 在变量声明时根据初始化表达式自动推断该类型的类型
  2. 声明函数时作为函数的返回值的占位符

简单的例子

#include<iostream>
#include<vector>
using namespace std;

template<class T, class U>void add(T t, U u){
	auto s = t + u;
    cout << "Type of t + u is" << typeid(s).name() << endl; 
}

int main(){
	auto a = 123;
    cout << "Type of a is" << typeid(a).name() << endl; 
    
    auto s("fred");
    cout << "Type of s is" << typeid(s).name() << endl; 

    vector<int> vec;
    auto iter = vec.begin();
    cout << "Type of iter is" << typeid(iter).name() << endl;
    
    add(101, 1.1);
}

注意事项:

  1. 使用auto关键字的变量必须有初始值

  2. 可以使用valatile, *(指针类型说明符), &(引用类型说明符), &&(右值引用)来修饰auto关键字

    	auto a = 10;
    	auto *pa = new auto(a);
    	auto **rpa = new auto(&a);
    	cout << typeid(a).name() << endl; 
    	cout << typeid(pa).name() << endl; 
    	cout << typeid(rpa).name() << endl; 
    

    在这里插入图片描述

  3. 函数参数和模板参数不能被声明为auto

  4. 使用auto关键字进行声明变量的类型,不能自动推导出顶层的CV-qualifiers和引用类型,除非显式声明

    #include<iostream>
    #include<typeinfo>
    using namespace std;
    int main(){
    	int i = 10;
    	int &r = i;
    	auto a = r;
    	a = 13;
    	cout << "i = " << i << "a =" << a << endl;
    	
    	
    	
    	auto &b = r;
    	b = 15;
    	cout << "i = " << i << "b =" << b << endl;
    }
    

  5. 使用auto使用auto关键字进行类型推导时,编译器会自动忽略顶层const,除非显示声明

    #include<iostream>
    #include<typeinfo>
    using namespace std;
    int main(){
    	const int c1 = 10;
    	auto c2 = c1;
    	
    //	c1 = 11;
    	c2 = 14;
    	cout << c1 << endl;
        // 报错,c1为const int类型,无法修改const变量
    	cout << c2 << endl;
        // 正确,c2为int类型
    	
    	// 显示声明
    	const auto c3 = c1;
    	c3 = 15;// 报错,c3为const int类型,无法修改const变量
    }
    
  6. 对于数组类型,auto关键字会推导为指针类型,除非被声明为引用

        int a[10];
        auto b = a;
        cout << typeid(b).name() << endl;   // 输出:int *
     
        auto &c = a;
        cout << typeid(c).name() << endl;   // 输出:int [10]
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值