参考链接:
https://blog.youkuaiyun.com/lixiaogang_theanswer/article/details/79983121
1.编程语言分类中,常有两种类型,分别是动态类型和静态类型
c\c++
语言是属于静态类型,因为采用c\c++
语言来进行开发的时候,都是采用先定义,后调用的形式;比如,给一个变量初始化,然后来调用该值,这里必须得先对该变量进行定义,告诉编译系统对其分配内存空间,然后才能使用。
int a = 10;
cout<<"a = "<<a<<endl;
这里先得对a
进行定义,其类型为int
,然后初始化赋值,再调用这样一个过程;但是若是python
,则完全不同。在python
里使用一个变量不必事先对其进行定义,在需要的时候临时用一个满足标识符的变量来赋值,然后就可调用,这样形式的语言称为动态语言。
val = 'name\n'
print 'hello, ' % val
结果:
hello,wrold
2.动态类型与静态类型的主要区别
注意区别在于:对变量进行类型检查的时间点。
静态类型: 类型检查主要发生在编译阶段;
动态类型:类型检查主要发生在运行阶段。
3.c++11
中的auto
新特性
示例:
#include<iostream>
#include<stdlib.h>
#include<string>
#include<map>
#include<vector>
#define PI 3.14159
using namespace std;
int printData(int a)
{
return ++a;
}
int main()
{
//1.基本数据类型推导
auto a = 11;
cout << "a = " << a << endl; //a int
auto b = "hello world.";
cout << "b = " << b << endl; //b char *
auto c = PI;
cout << "c = " << c << endl; //c double
//2.函数返回值
auto d = printData(100);
cout << "d = " << d << endl; //c int
//3.STL标准模板库
vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8 };
vector<int> _vec = { 11, 12, 13, 14, 15 };
auto it = vec.begin(); //it vector<int>::iterator 迭代器类型
while (it != vec.end())
{
cout << *it << " ";
++it;
}
cout << "============================" << endl;
map<int, vector<int> > _map;
_map.insert(pair<int, vector<int>>(1, vec));
_map.insert(pair<int, vector<int>>(2, _vec));
for (auto it1 = _map.begin(); it1 != _map.end(); ++it1) //it1 map<int,vector<int> >::iterator
{
cout << it1->first << endl;
auto it2 = it1->second.begin(); //it2 vector<int>::iterator
while (it2 != it1->second.end())
{
cout << *it2 << " ,";
++it2;
}
cout << endl;
}
system("pause");
return 0;
}
4. 自动推导类型auto
的使用限制
(1)对于函数,auto
不能是形参的类型。
int printData(auto a) //auto作为形参类型,编译报错
{
return ++a;
}
(2)对于结构体,非静态成员变量的类型不能是auto
类型。
struct Student
{
auto m_b; //编译报错
};
(3)声明auto
数组
auto arr[10]; //编译报错
(4)实例化模板的时候,使用auto
作为模板参数
template <auto T> //编译报错
除了上面这4个限制外(形参,数组,结构体非静态成员变量,模板参数),其他的场景都可以采用自动推导类型auto
,这在项目开发中大大提高了简便和效率。