目录
一.类型别名的思考:
随着程序越来越复杂,程序中用到的类型也越来越复杂,经常体现在:
1. 类型难于拼写
2. 含义不明确导致容易出错
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> m{ { "apple", "苹果" }, { "orange", "橙子" },
{"pear","梨"} };
std::map<std::string, std::string>::iterator it = m.begin();
while (it != m.end())
{
//....
}
return 0;
}
std::map<std::string, std::string>::iterator 是一个类型,但是该类型太长了,特别容易写错。可以通过typedef
给类型取别名,比如:
#include <string>
#include <map>
typedef std::map<std::string, std::string> Map;
int main()
{
Map m{ { "apple", "苹果" },{ "orange", "橙子" }, {"pear","梨"} };
Map::iterator it = m.begin();
while (it != m.end())
{
//....
}
return 0;
}
但是typedef在使用时容易出现错误
typedef char* pstring;
int main()
{
const pstring p1;
const pstring* p2;
return 0;
}
二.auto的介绍
在早期C/C++
中
auto
的含义是:使用
auto
修饰的变量,是具有自动存储器的局部变量
,但遗憾的是一直没有人去使用它,大家可思考下为什么?
C++11中,标准委员会赋予了
auto
全新的含义即:
auto
不再是一个存储类型指示符,而是作为一个新的类型
指示符来指示编译器,
auto
声明的变量必须由编译器在编译时期推导而得.
。
![](https://i-blog.csdnimg.cn/blog_migrate/33e46f983a6cacf9c2151b2f4c033a57.png)
![](https://i-blog.csdnimg.cn/blog_migrate/775e854c345a2c63543588060d6fa3a7.png)
使用规则:
![](https://i-blog.csdnimg.cn/blog_migrate/44f932c45dc80558f36954e71619eee6.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71159bfefda534e5370e5b55c2211682.png)
2.
在同一行定义多个变量
当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对
第一个类型进行推导,然后用推导出来的类型定义其他变量。
void TestAuto()
{
auto a = 1, b = 2;
auto c = 3, d = 4.0; // 该行代码会编译失败,因为c和d的初始化表达式类型不同
}
auto
不能推导的场景
1.
auto
不能作为函数的参数
// 此处代码编译失败,auto不能作为形参类型,因为编译器无法对a的实际类型进行推导
void TestAuto(auto a)
{}
2.
auto
不能直接用来声明数组
void TestAuto()
{
int a[] = {1,2,3};
auto b[] = {4,5,6};
}
3.
为了避免与
C++98
中的
auto
发生混淆,
C++11
只保留了
auto
作为类型指示符的用法
4. auto
在实际中最常见的优势用法就是跟以后会讲到的
C++11
提供的新式
for
循环,还有
lambda
表达式等进行配合使用。
void TestFor()
{
int array[] = { 1, 2, 3, 4, 5 };
for(auto& e : array)
e *= 2;
for(auto e : array)
cout << e << " ";
return 0;
}