網站首頁 編程語言 正文
一.auto推導規則4點
(1) 引用不是類型,因此auto不能推斷出引用
int a = 1;
int& b = a;// b-> int& 用->表示推導出類型,下同
auto c = b;// c->int
(2)auto 在推斷引用的類型時,會直接將引用替換為引用指向的對象。
引用不是對象,任何引用的地方都可以直接替換為引用指向的對象。
int a = 10;
const int& b = a ;// b-> const int&
auto c = b; // c-> int
//相當于 auto c = a;
由于在傳遞值時,修改這個值不會對原有的數據造成影響,而傳遞引用時,修改這個值會對修改原有的數據。
(3)auto 關鍵字推斷類型時,如果沒有引用符號,那么會忽略值類型的const修飾,而保留修飾指向對象的const
const int i =1;
auto j = i;//j-> int
int a ;
const int* const pi = &a;//第一個const 修飾指針的指向的對象,第二個const修飾pi指向的值。
//會忽略第二個const。
auto pi2 = pi; // pi2 -> int* const
(4)如果有引用符號,那么值類型的const和指向的const都會保留。
int i = 1;
const int* const j = &i;
auto &k = j; //a->const int const &
具體推導例子:
int x = 10;
? | 推導表達式: | 推導出變量數據類型: | auto被推導的類型: |
1 | auto? *a = &x; | ???? a?? 被推導為 :int * | auto 推導為: int |
2 | auto? b =? &x; | ???? b? 被推導為: int* | auto 推導為: int * |
3 | auto &c = x ; | ???? c? 被推導為: ? int& | auto 推導為: int |
4 | auto d = c; | ???? d 被推導為:? int | auto 推導為: int |
5 | const auto e= x; | ???? e 被推導為: const int | auto 推導為:??? int |
6 | auto f = e; | ???? f 被推導為: int | auto 推導為:??? int |
7 | const auto& g = x; | ???? g 被推導為: const int& | auto 推導為:??? int |
8 | auto& h = g;? | ???? h 被推導為:const int& | auto 推導為:??? int |
注意: auto聲明的變量必須馬上初始化,因為在編譯階段編譯器就將其類型推導出來。
auto a;error
二.auto的使用時機
(1)用于推導容器的迭代器:
原本不使用類型推導我們對容器的遍歷:
for(vector<int>::iterator it = vec.begin(); it! = vec.end(); it++)
{
cout<<"vec:"<< *it <<endl;
}
使用auto自動類型推導后對容器的遍歷:
for(auto it = vec.begin(); it! = vec.end(); it++ )
{
cout>>"vec:"<<*it<<endl;
}
是不是清爽了很多,利用auto自動類型推導,就不需要寫一堆迭代器類型了。
(2)書寫泛性函數
不知道程序使用時,傳入的參數是什么類型時,用auto可以為我們節省不少工作量。
(3)用于函數的返回值類型后置:
和decltypr配合使用,在后文講述。
原文鏈接:https://blog.csdn.net/zooo520/article/details/124675241
相關推薦
- 2022-12-11 詳解Android?GLide圖片加載常用幾種方法_Android
- 2022-04-24 torch.utils.data.DataLoader與迭代器轉換操作_python
- 2022-03-14 關于log4j日志擴展---自定義PatternLayout(log4j自定義日志級別)
- 2022-11-30 Go語言k8s?kubernetes使用leader?election實現選舉_Golang
- 2022-09-18 golang實現文件上傳并轉存數據庫功能_Golang
- 2022-12-09 python進階collections標準庫使用示例詳解_python
- 2022-03-23 Asp.Net?Core?使用Monaco?Editor?實現代碼編輯器功能_實用技巧
- 2022-01-27 插入數據庫某個字段之前判斷是否重復
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支