1. auto
1.typeid(*).name() -----(类型的查看)
l类型 | 显示 |
---|---|
int | i |
float | f |
char* | PKc (pointer–const–char) |
int arr[] | typeid(arr).name() |
typeid(string).name() | 好长的字符串(string); |
typeid(vector).name() | 好长的字符串(vector) |
typeid(Simple).name() | 类的话(*个字符) |
auto it = vec.begin();cout << typeid(it).name() << endl; | 好长的字符串(iterator) |
func | func |
注意:
(1)auto 进行变量定义必须初始化;
auto m1= 10;//必须要初始化;
(2)auto不能推导数组;
auto m4[] = {
1,2,3,4,5,6};
cout << typeid(m4).name() << endl;
2.基于范围的for循环
for(auto a:arr){
cout << a << " ";
}
cout << endl;
3.定义迭代器
vector<int> vec = {
1,2,3};
//vector<int>::iterator it = vec.begin(); //不推荐
auto it = vec.begin(); //推荐
cout << typeid(it).name() << endl;
(4) 定义函数指针
auto func = Func;
func();
cout << typeid(func).name() << endl;
完整代码见001——auto.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Simple /*final*/{
// 禁止继承
};
void Func(){
cout<< __func__<<endl;
}
int main(){
// auto 自动推导变量类型
int n = 10;
cout << typeid(n).name() << endl;//i
float f;
cout << typeid(f).name() << endl; //f
const char* hello = "abc";
cout << typeid(hello).name() << endl; //PKc (pointer--const--char)
int arr[] = {
1,2,3,4,5};
cout << typeid(arr).name() << endl;//Ai5(array_int_5)
cout << typeid(string).name() <<<