1.auto

auto

auto 的自動類型推導,用於從初始化表達式中推斷出變量的數據類型。從這個意義上講,auto並非一種“類型”聲明,而是一個類型聲明時的“佔位符”,編譯器在編譯時期會將 auto 替換爲變量實際的類型。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
float foo() {}
void func(vector<string> & tmp)
{
	//4.推到容器的類型,auto自動推到類型爲vector<string>,寫起來方便
	for (auto i = tmp.begin(); i < tmp.end(); i++)
	{
		// 函數體
	}
}

int main()
{
//1.推到變量的類型
auto x = 1; // x的類型爲 int

//2.推到函數返回值的類型
auto y = foo(); // y 的類型爲 float

//3.推到自定義結構體的類型
struct Test
{
  int i;
}str;
auto str1 = str; // str1 的類型是 struct Test

return 0;
}

注意點:
1.定義變量時,必須初始化
2.VS2017 不支持函數形參是auto變量
3.auto變量不能作爲自定義類型的成員變量,初始化了了也不行
4.auto不能用於數組,不能auto數組
5.模板實例化不能使auto類型,初始化了也不行
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章