c++ auto类型用法总结

本文详细介绍了C++中的auto关键字,包括它的用途、简要理解、用法及优势等。并给出了多个实例帮助理解如何使用auto简化复杂类型的变量声明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、用途


auto是c++程序设计语言的关键字。用于两种情况

(1)声明变量时根据初始化表达式自动推断该变量的类型

(2)声明函数时函数返回值的占位符


二、简要理解


auto可以在声明变量时根据变量初始值的类型自动为此变量选择匹配的类型。

举例:对于值x=1;既可以声明: int x=1 或 long x=1,也可以直接声明 auto x=1


三、用法


根据初始化表达式自动推断被声明的变量的类型,如:

auto f = 3.14;  //double
auto s("hello");  //const char*
auto z = new auto(9);  //int *
auto x1 = 5, x2 = 5.0, x3 = 'r';   //错误,必须是初始化为同一类型

但是,这么简单的变量声明类型,不建议用auto关键字,而是应更清晰地直接写出其类型。


auto关键字更适用于类型冗长复杂、变量使用范围专一时,使程序更清晰易读。如:

 std::vector<int> vect; 
 for(auto it = vect.begin(); it != vect.end(); ++it)
 {  //it的类型是std::vector<int>::iterator
    std::cin >> *it;
  }


或者保存lambda表达式类型的变量声明:

  auto ptr = [](double x){return x*x;};//类型为std::function<double(double)>函数对象


四、优势


1)拥有初始化表达式的复杂类型变量声明时简化代码。

比如:

#include <string>  
#include <vector>  
void loopover(std::vector<std::string>&vs)  
{  
    std::vector<std::string>::iterator i=vs.begin();  
    for(;i<vs.end();i++)  
    {  
      
    }  
  
}

变为:

#include <string>  
#include <vector>  
void loopover(std::vector<std::string>&vs)  
{  
    for(  auto i=vs.begin();;i<vs.end();i++)  
    {  
      
    }  
  
}  

使用std::vector<std::string>::iterator来定义i是C++常用的良好的习惯,但是这样长的声明带来了代码可读性的困难,因此引入auto,使代码可读性增加。并且使用STL将会变得更加容易


(2)可以避免类型声明时的麻烦而且避免类型声明时的错误。

但是auto不能解决所有的精度问题。比如:

#include <iostream>  
using namespace std;  
int main()  
{  
   unsigned int a=4294967295;//最大的unsigned int值  
   unsigned int b=1;  
   auto c=a+b;  
   cout<<"a="<<a<<endl;  
   cout<<"b="<<b<<endl;  
   cout<<"c="<<c<<endl;  
}  


上面代码中,程序员希望通过声明变量c为auto就能解决a+b溢出的问题。而实际上由于a+b返回的依然是unsigned int的值,姑且c的类型依然被推导为unsigned int,auto并不能帮上忙。这个跟动态类型语言中数据hi自动进行拓展的特性还是不一样的。


五、注意的地方

(1)可以用valatile,pointer(*),reference(&),rvalue reference(&&) 来修饰auto

auto k = 5;  
auto* pK = new auto(k);  
auto** ppK = new auto(&k);  
const auto n = 6;  


(2)用auto声明的变量必须初始化


(3)auto不能与其他类型组合连用


(4)函数和模板参数不能被声明为auto


(5)定义在堆上的变量,使用了auto的表达式必须被初始化

int* p = new auto(0); //fine  
int* pp = new auto(); // should be initialized  
auto x = new auto(); // Hmmm ... no intializer  
auto* y = new auto(9); // Fine. Here y is a int*  
auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)  


(6)以为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid


(7)定义在一个auto序列的变量必须始终推导成同一类型

auto x1 = 5, x2 = 5.0, x3='r';  /<span style="font-family: Arial, Helvetica, sans-serif;">/错误,必须是初始化为同一类型</span>


(8)auto不能自动推导成CV-qualifiers (constant & volatile qualifiers)


(9)auto会退化成指向数组的指针,除非被声明为引用


### C++ 中 `auto` 关键字的用法 在现代 C++(特别是自 C++11 起),`auto` 是一种用于自动推导变量类型的机制。它允许编译器根据初始化表达式的类型来决定变量的实际类型,从而减少显式指定复杂类型的需求并提高代码可读性和维护性。 #### 基本语法 当声明一个带有 `auto` 的变量时,必须对其进行初始化以便编译器能够推断其具体类型: ```cpp auto variable_name = initializer; ``` 如果未提供初始值,则会引发编译错误,因为无法确定变量的具体类型。 #### 类型推导规则 - **简单数据类型** 对于基本的数据类型如整数、浮点数等,`auto` 可以直接从赋值操作中得出确切类型。 ```cpp auto i = 42; // int auto d = 3.14; // double ``` - **指针与引用** 当涉及指针或引用时,`auto` 同样能正确识别它们所指向的对象类别及其修饰符(const/volatile)。例如,在下面的例子中展示了如何处理常量字符指针的情况[^3]: ```cpp const char* str = "example"; auto pStr = str; // deduced as 'const char*' ``` - **容器迭代器** 使用 STL 容器时经常遇到复杂的迭代器定义语句,此时利用 `auto` 将极大简化书写过程而不必关心底层实现细节。 ```cpp std::vector<int> vec{1, 2, 3}; for(auto it=vec.begin();it!=vec.end();++it){ std::cout<<*it<<"\n"; } ``` - **返回类型推测** 函数模板或者 lambda 表达式的返回值也可以借助 `auto` 来动态调整最终产出形式,这尤其适用于泛型编程场景下未知的确切输出结构。 ```cpp template<typename T> auto add(T a,T b)->decltype(a+b){return a+b;} [](int x,int y) -> decltype(x+y) { return x + y; }; ``` 需要注意的是虽然 `auto` 提供了很多便利之处但是过度依赖可能会降低程序清晰度因此建议仅在必要时候采用此特性替代传统方式明确写出所需对象种类信息。 #### 示例代码片段展示不同情境下的应用实例: ```cpp #include <iostream> #include <vector> // Basic type deduction with auto. void basicDeduction(){ auto num = 10; // Deduces to int auto pi = 3.14f; // Deduces to float std::cout << "num: " << num << ", pi: " << pi << '\n'; } // Using auto with pointers and references. void pointerReferenceUsage(){ int value = 42; auto valPtr = &value; // Deduces to int* const int cValue = 100; auto cValRef = cValue; // Deduces to const int& (*valPtr)++; //(*&cValue)++; // Error! Cannot modify constant. std::cout << "*valPtr: " << *valPtr << ", cValRef: " << cValRef << '\n'; } // Utilizing auto within loops over containers. void containerIterationExample(){ std::vector<std::string> words{"hello","world"}; for(const auto& word : words){ std::cout << word << "\t"; } } ``` 以上示例涵盖了多种实际开发中的常见情况,通过这些例子可以更好地理解 `auto` 在不同类型环境里的表现特征以及适用范围。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值