C++11新特性总结
本博客参考侯捷老师的视频进行的总结。详细请观看侯捷老师的视屏。
测试版本:cout
文章目录
1、Variadic Templates(数量不定的模板参数)
表现形式:template <typename… Types>
表达效果:接收不定数量的不同类型的参数。
使用样例:
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
// 用于print递归的终结,最后无参数后调用该函数结束递归。
void print()
{
}
template <typename T, typename... Types>
void print(const T& firstArg, const Types&... args)
{
cout << firstArg << endl;
print(args...);
}
int main()
{
// bitset生成二进制数据
print(1, 2, 3, 4, bitset<16>(377), "hello", "world", "!");
return 0;
}
2、nullptr and nullptr_t
表示指针,代替NULL,编译器识别的时候不再认为是0,而是认为传入的是指针。可用于模板的偏特化等。
3、auto
占位符,可以不用指定类型,让编译器按照实际传入类型进行指定。不建议过多使用,对于比较长的类型或过于复杂的类型可以使用。其它基本类型建议自己掌握。
4、Initializer_list
可以传入多个参数,用于容器初始化,或者当作参数使用。基本类型是array实现的,所以传入的应该属于同一数据类型。
使用样例:
#include <iostream>
#include <string>
using namespace std;
// 作为参数列表
void printArr(initializer_list<int> vals)
{
// 可以使用迭代器进行遍历
for(auto p = vals.begin(); p != vals.end(); ++p)
{
cout << *p << endl;
}
}
int main()
{
int a{5};
cout << a << endl;
printArr({1, 2, 3, 4, 5});
return 0;
}
5、explicit
告诉编译器不要自动使用构造函数,必须手动使用构造函数才会调用。
#include <iostream>
#include <string>
#include <bitset>
include <vector>
using namespace std;
struct Complex
{
int real, imag;
explicit
Complex(int re, int im=0):real(re), imag(im)
{}
Complex operator+ (const Complex& x)
{
return (Complex((real + x.real), (imag + x.imag)));
}
};
int main()
{
Complex c1(12, 5);
Complex c2 = c1 + 5;
return 0;
}
[Error] no match for ‘operator+’ (operand types are ‘Complex’ and ‘int’)
6、for
#include <iostream>
#include <string>
#include <bitset>
include <vector>
using namespace std;
void newFor()
{
int a[7] = { 2, 3, 5, 6, 8, 2, 1 };
vector<int> vec(a, a + 7);
// 类似python的for i in [2, 3, 5, 6, 8, 2, 1]
// 变量 : 容器
// 可以把容器中的每一个变量作为一次循环的参数
// 多少个变量进行多少次循环,每个变量作为一次循环参数
for (int i : {2, 3, 5, 6, 8, 2, 1})
{
cout << i << endl;
}
cout << endl;
// 使用引用可以对数据进行修改,相当于指向该数据,速度也较快
for (auto& elem : vec)
{
elem *= 3;
}
for (auto elem : vec)
{
cout << elem << endl;
}
}
int main()
{
newFor();
return 0;
}
7、=default or =delete
两者不能并存
类名(const 类名&)=default;
如果自己写了构造函数编译器就不会提供默认构造函数,使用=default可以让编译器提供默认构造函数。
类名(const 类名&)=delete;
表明不需要编译器提供默认构造函数。
提供搬移构造函数
类名(类名&&)=default;
不要=操作符重载的搬移构造函数
类名& operator=(const 类名&&)=delete;
No-Copy
将拷贝构造和拷贝赋值都=delete就可以不允许拷贝
Private-Copy
可以将拷贝构造和拷贝赋值声明为private,只允许friend和member使用。
8、Alias Template(template typedef)
template <typename T>
using Vec = std::vector