💡 如果想阅读最新的文章,或者有技术问题需要交流和沟通,可搜索并关注微信公众号“希望睿智”。

概述

C++ 11中引入了许多简化编程工作的语法上的新特性,我们暂且美其名曰:“语法甜点”。下面,我们将对这些“语法甜点”一一进行介绍。


语法甜点1:序列for循环

序列for循环是一种简化的for循环,可用于遍历一组序列,包括:各种容器、string、数组、初始化列表以及由begin和end函数定义的序列。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> vctTemp{1, 2, 3};
    for (auto a : vctTemp)
    {
        cout << a << endl;
    }

    return 0;
}


语法甜点2:成员变量初始化

与Java、C#中的用法一样,可以对成员变量进行就地初始化。

class CPerson
{
private:
    int m_nAge = 10;
    string m_strName = "Mike";
};


语法甜点3:统一的初始化语法

在引入C++ 11之前,有各种不同的初始化语法。在C++ 11中,仍可以使用这些初始化语法,但也可以选择使用新引入的统一的初始化语法。统一的初始化语法用一对大括号{}表示,使用{}初始化语法还可有效地避免窄转换。

#include <iostream>
#include <vector>
using namespace std;

class CPerson
{
public:
    int m_nAge = 10;
    string m_strName = "Mike";
};

int main()
{
    int a{5};
    char c{'X'};
    int p[5] = {1, 2, 3, 4, 5};
    vector<int> vctTemp{1, 2, 3};
    CPerson person{10, "Mike"};
    // b赋值成5,发生了窄转换
    int b = 5.3;
    // 会提示编译错误,避免了窄转换
    int d{5.3};
    return 0;
}


语法甜点4:nullptr

nullptr是C++ 11中新加的一个关键字,用于标识空指针。引入nullptr后,可以解决某些函数重载时的二义性问题。

#include <iostream>
using namespace std;

void Test(int a)
{
    cout << a << endl;
}

void Test(char *p)
{
    cout << p << endl;
}

int main()
{
    int *p = nullptr;
    int *q = NULL;
    // 两个指针值是相等的,bEqual为true
    bool bEqual = (p == q);
    // 编译失败,nullptr不是转换为int
    int a = nullptr;

    // 在C++ 98中编译失败,有二义性;在C++ 11中调用F(int)
    Test(0);
    // 调用F(char *)
    Test(nullptr);

    return 0;
}


语法甜点5:委托构造函数

在引入C++ 11之前,如果某个类有多个重载的构造函数,且这些构造函数中有一些共同的初始化逻辑,通常都需要再编写一个带参数的初始化函数,然后在这些构造函数中调用这个初始化函数。在C++ 11中,再也不用这么麻烦了。我们可以实现一个最基础的构造函数,其他构造函数都调用这个构造函数。

#include <iostream>
#include <sstream>
using namespace std;

class CPerson
{
public:
    CPerson() : CPerson(0, "") { NULL; }
    CPerson(int nAge) : CPerson(nAge, "") { NULL; }
    CPerson(int nAge, const string &strName)
    {
        stringstream ss;
        ss << strName << "is " << nAge << "years old.";
        m_strInfo = ss.str();
    }

private:
    string m_strInfo;
};

int main()
{
    CPerson person(10, "Mike");
    return 0;
}