初始化列表 Initializer List
std::vector<int> v = { 1, 2, 3 };
std::list<int> l = { 1, 2, 3 };
std::set<int> s = { 1, 2, 3 };
std::map<int, std::string> m = { {1, "a"}, {2, "b"} };
类型推导 Auto Type
auto i = 1; // int
auto d = 1.1; // double
auto s = "hi"; // const char*
auto a = { 1, 2 }; // std:: initializer_list<int>
遍历 for
QVector<int> num = {1,2,3};
for(int i:num)
{
qDebug() << i;
}
//之前是复制变量,也可以引用后修改
for(int &i:num)
{
if(i==1)
{
i = 10;
}
}
空指针 nullptr
以往我们使用NULL表示空指针。它实际上是个为0的int值。下面的代码会产生岐义:
void f(int i) {} // chose this one
void f(const char* s) {}
f(NULL);
为此C++ 11新增类型nullptr_t,它只有一个值nullptr。上面的调用代码可以写成:
void f(int i) {}
void f(const char* s) {} // chose this one
f(nullptr);
强类型枚举 enum class
enum class Direction {
Left, Right
};
enum class Answer {
Right, Wrong
};
auto a = Direction::Left;
auto b = Answer::Right;
if (a == b)
std::cout << "a == b" << std::endl;
else
std::cout << "a != b" << std::endl;
静态断言 static assert
static_assert可在编译时作判断。
static_assert( size_of(int) == 4 );
构造函数的相互调用 delegating constructor
class A {
public:
A(int x, int y, const std::string& name) : x(x), y(y), name(name) {
if (x < 0 || y < 0)
throw std::runtime_error("invalid coordination");
// other stuff
}
A(int x, int y) : x(x), y(y), name("A") {
if (x < 0 || y < 0)
throw std::runtime_error("invalid coordination");
// other stuff
}
A() : x(0), y(0), name("A") {
// other stuff
}
private:
int x;
int y;
std::string name;
};
禁止重写 final
class A {
public:
virtual void f1() final {} //此虚函数禁止被重写
};
class B : public A {
virtual void f1() {} //错误
};
class A final { //此类函数禁止被重写
};
class B : public A { //错误
};
显式声明重写 override
class A {
public:
virtual void f1() const {}
};
class B : public A {
virtual void f1() override {}
};
编译报错,提示找不到重写函数f1(),因为少了const。override相当于做了检查
定义成员初始值
class A {
public:
int m = 1;
};
默认构造函数 default
当一个class有自定义构造函数时,编译器就不会自动生成一个无参构造函数。现在可以通过default关键字强制要求生成这个构造函数。
class A {
public:
A(int i) {}
A() = default;
};
删除构造函数 delete
class A {
public:
A() = delete;
};
常量表达式 constexpr
int size() { return 3; }
int a[size()];
上面的代码编译失败,因为静态数组的大小必须在编译期确定。改成:
constexpr int size() { return 3; }
int a[size()];
加上了constexpr,函数size变成在编译期计算,返回值被看成一个常量。
Lambda函数
capture mutable ->return-type{statement}
1.[capture]:捕捉列表。捕捉列表总是出现在Lambda函数的开始处。实际上,[]是Lambda引出符。编译器根据该引出符判断接下来的代码是否是Lambda函数。捕捉列表能够捕捉上下文中的变量以供Lambda函数使用;
2.(parameters):参数列表。与普通函数的参数列表一致。如果不需要参数传递,则可以连同括号“()”一起省略;
3.mutable:mutable修饰符。默认情况下,Lambda函数总是一个const函数,mutable可以取消其常量性。在使用该修饰符时,参数列表不可省略(即使参数为空);
4.->return-type:返回类型。用追踪返回类型形式声明函数的返回类型。我们可以在不需要返回值的时候也可以连同符号”->”一起省略。此外,在返回类型明确的情况下,也可以省略该部分,让编译器对返回类型进行推导;
5.{statement}:函数体。内容与普通函数一样,不过除了可以使用参数之外,还可以使用所有捕获的变量。