类型别名(type alias)是一个名字,使用typedef不会真正地建立一种新的数据类型,它只是已经存在数据类型的一个新名称。
语法:ios
typedef type name;
其中type是c++中的数据类型,name是这个类型的一个别名。
C++11提供了引用的功能,关于引用的详细介绍能够参考笔者以前的文章。引用为变量提供别名,typedef则是为类型提供别名。
例如:c++
#include <iostream> int main(){ int m = 10;//使用int定义变量m typedef int integer;//建立一个int的别名为integer integer n = 20;//使用integer定义变量n typedef integer integer_type;//建立一个integer的别名为integer_type integer_type o = 30;//使用integer_type定义变量o std::cout << "m + n + o = " << (m+n+o) << std::endl;//运算 return 0; }
输出结果:spa
m + n + o = 60
上面有两个别名integer和integer_type,integer_type有integer建立而来,integer_type和integer都是属于int类型。指针
c++11还为提供别名提供了另外一种更为简便的方法—别名声明(alias declaration),例如:c++11
using integer = int; // integer是int的同义词
这种方法的规则是用using关键字做为别名的开始,其后紧跟别名和等号。code
auto是c++11标准定义的一个类型推断的关键字,auto可以让编译器自动去分析表达式所属的类型,与特定的数据类型不一样(好比double),让编译器经过初始值来推算变量的类型。显然auto定义必须有初始值。
好比:blog
#include <iostream> #include <typeinfo> #include <set> using namespace std; int main() { auto x = 4; auto y = 3.37; auto ptr = &x; cout << "x type is : " << typeid(x).name() << endl << "y type is : " << typeid(y).name() << endl << "ptr type is : " << typeid(ptr).name() << endl; cout << "--------------------------" << endl; set<string> strs; strs.insert({"green","blue","red"}); for(auto it = strs.begin();it != str.end();it++){//遍历容器中的元素 cout << *it << " "; } cout << "--------------------------" << endl; //r是一个int引用类型 auto &r = x; cout << "r type is : " << typeid(r).name() << endl; return 0; }
输出结果:编译器
x type is : i
y type is : d
ptr type is : Pi
--------------------------
blue green red
--------------------------
r type is : i
上面的i表示int,d表示double,Pi表示int*(int类型的指针)。string
decltype也是c++11提供的一个关键字,它能够从变量或表达式中提取类型。it
int f() { return 10; } int main(){ decltype(f()) val;//f()返回值是int类型,val是int类型 const int &v = 10; decltype(v) rval;//错误,rval 是引用类型,必需要初始化 int pv = 10; int *p = &pv; decltype(p) pp;//正确,pp是int*类型。 decltype(*p) c;//错误,c是int&类型(int引用类型),必需要初始化 return 0; }
若是表达式是解引用操做(*),那么decltype将会获得引用类型。如上面的decltype(*p)。
若是decltype里面有两个括号,那么是一个引用类型
decltype((i)) d;//错误,d是int&,必需要初始化。 decltype(i) e;//正确,e是一个(未初始化)int。
注意:
decltype((variable))(注意是双括号)的结果永远是引用,而decltype(variable)结果只有当variable自己是引用时才是引用。