c++中的auto关键字
生活随笔
收集整理的這篇文章主要介紹了
c++中的auto关键字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
auto的屬性特征
#include <iostream>
using namespace std;int main() {//1.auto 變量必須在定義時初始化,類似于constauto i1 = 0; auto i2 = i1;//auto i3; //錯誤,必須初始化//2.如果初始化表達式是引用,則去除引用語義int a1 = 10;int &a2 = a1; // a2是引用auto a3 = a2; // a3是int類型,而不是引用auto &a4 = a1; // a4是 引用//3.去除頂層constconst int b1 = 100;auto b2 = b1; // b2 是 intconst auto b3 = b1; // b3是 const int//4.帶上底層constauto &b4 = b1; // b4 是 const int 的引用//5.初始化表達式為數組時,推導類型為指針int arr[3] = { 1,2,3 };auto parr = arr; //parr 是 int * 類型cout << typeid(parr).name() << endl;//6.表達式為數組且auto帶上&,推導類型為數組auto &rarr = arr; //rarr 是 int [3]cout << typeid(rarr).name() << endl;//7.函數參數類型不能是 auto//func(auto arg); //錯誤//8.auto并不是一個真正的類型,編譯時確定//sizeof(auto); 錯誤return 0;
}
auto使用實例
auto推導的一個最大的優勢在于擁有初始化表達式的復雜類型變量聲明時簡化代碼
#include <iostream>
#include <vector>
#include <string>
using namespace std;int main() {vector<string> vs ={ "all","people","like","c++" };for (vector<string>::iterator i = vs.begin(); i != vs.end(); i++)cout << *i << " ";cout << endl;for (auto i = vs.begin(); i != vs.end(); i++) cout << *i << " ";cout << endl;for (auto &s : vs)cout << s << " ";cout << endl;return 0;
}
auto的詳細參考
auto詳細解釋
總結
以上是生活随笔為你收集整理的c++中的auto关键字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++中的vector的常见使用
- 下一篇: c/c++的内存四区