c++中的auto关键字
生活随笔
收集整理的這篇文章主要介紹了
c++中的auto关键字
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
auto的屬性特征
#include <iostream>
using namespace std;int main() {//1.auto 變量必須在定義時(shí)初始化,類似于constauto i1 = 0; auto i2 = i1;//auto i3; //錯(cuò)誤,必須初始化//2.如果初始化表達(dá)式是引用,則去除引用語(yǔ)義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.初始化表達(dá)式為數(shù)組時(shí),推導(dǎo)類型為指針int arr[3] = { 1,2,3 };auto parr = arr; //parr 是 int * 類型cout << typeid(parr).name() << endl;//6.表達(dá)式為數(shù)組且auto帶上&,推導(dǎo)類型為數(shù)組auto &rarr = arr; //rarr 是 int [3]cout << typeid(rarr).name() << endl;//7.函數(shù)參數(shù)類型不能是 auto//func(auto arg); //錯(cuò)誤//8.auto并不是一個(gè)真正的類型,編譯時(shí)確定//sizeof(auto); 錯(cuò)誤return 0;
}
auto使用實(shí)例
auto推導(dǎo)的一個(gè)最大的優(yōu)勢(shì)在于擁有初始化表達(dá)式的復(fù)雜類型變量聲明時(shí)簡(jiǎn)化代碼
#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的詳細(xì)參考
auto詳細(xì)解釋
總結(jié)
以上是生活随笔為你收集整理的c++中的auto关键字的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++中的vector的常见使用
- 下一篇: c/c++的内存四区