[C++] C++11详解 (一)

标题:[C++] C++11详解 (一)

@水墨不写bug


[C++] C++11详解 (一)_第1张图片


目录

前言

一、列表初始化

二、STL的初始化列表(initializer_list —— Cplusplus.com)

三、声明方式(auto、decltype、nullptr)

1.auto

​编辑 2.decltype


正文开始:

前言

        从本文开始,我们认识进入一个重要的知识:C++11的新语法。本文旨在讲解C++11的新语法,让大家对近年来C++的发展有一个纵向的认识。


一、列表初始化

        C++11中,你几乎可以使用花括号“{}”对大多数容器进行初始化:(并且 赋值符号“=”可以省略)

        准确来说:如果STL中一种容器,它有初始化列的构造函数,就意味着可以使用初始化列对它初始化:

#include
#include
#include
#include
#include
using namespace std;
int main()
{
	string s = {'a','b','c','d','\0'};	
	//string s{'a','b','c','d','\0'};
	
	vector v = {1,2,3,4};
	//vector v{1,2,3,4};

	map m = {{1,2},{2,3}};
	//map m{{1,2},{2,3}};

	set se = {1,2};
	//set se{1,2};

	return 0;
}

        此外,对于数组,任意的内置类型和自定义类型,也可用初始化列进行初始化:

struct Point
{
    int _x;
    int _y;
};

int main()
{
    int x1 = 1;
    int x2{ 2 };

    int array1[]{ 1, 2, 3, 4, 5 };
    int array2[5]{ 0 };

    Point p{ 1, 2 };

    // C++11中列表初始化也可以适用于new表达式中
    int* pa = new int[4]{ 0 };

    return 0;
};

 创建对象时也可以使用列表初始化方式调用构造函数初始化:

class Date
{
public:
    Date(int year, int month, int day)
        :_year(year)
        ,_month(month)
        ,_day(day)
    {
        cout << "Date(int year, int month, int day)" << endl;
    }
private:
    int _year;
    int _month;
    int _day;
};

int main()
{
    Date d1(2022, 1, 1); // old style

    // C++11支持的列表初始化,这里会调用构造函数初始化
    Date d2{ 2022, 1, 2 };
    Date d3 = { 2022, 1, 3 };
    return 0;
}

二、STL的初始化列表(initializer_list —— Cplusplus.com)

        C++11中,新增了initializer_list这种容器,它拥有自己的构造,begin(),end()等迭代器。

        一般来说,initializer_list用于作为构造函数的参数;这也是C++11中,不少容器新增初始化列的构造函数的原因。

        std::initializer_list作为参数的构造函数,这样初始化容器对象就更方便了。也可以作为operator=的参数,这样就可以用大括号赋值:

int main()
{
    vector v = { 1,2,3,4 };
    list lt = { 1,2 };

    // 这里{"sort", "排序"}会先初始化构造一个pair对象
    map dict = { {"sort", "排序"}, {"insert", "插入"} };

    // 使用大括号对容器赋值
    v = {10, 20, 30};
    
    return 0;
}

三、声明方式(auto、decltype、nullptr)

1.auto

        在C++98中auto是一个存储类型的说明符,表明变量是局部自动存储类型,但是局部域中定义局部的变量默认就是自动存储类型,所以auto就没什么价值了。

        C++11中废弃auto原来的用法,将其用于实现自动类型推测。这样要求必须进行显示初始化,让编译器将定义对象的类型设置为初始化值的类型。

int main()
{
    int i = 10;

    auto p = &i;
    //p是int*
    auto pf = strcpy;
    //pf是char*

    map dict = { {"sort", "排序"}, {"insert", "插入"} };
    //map::iterator it = dict.begin();

    //使得声明类型不再是一件头大的事
    auto it = dict.begin();

    return 0;
}

[C++] C++11详解 (一)_第2张图片 2.decltype

        关键字decltype将变量的类型声明为表达式指定的类型:

// decltype的一些使用使用场景
template
void F(T1 t1, T2 t2)
{
    decltype(t1 * t2) ret;
    cout << typeid(ret).name() << endl;
}

int main()
{
    const int x = 1;
    double y = 2.2;

    decltype(x * y) ret; // ret的类型是double
    //如果是int乘以int,则推测为int
    //这样就方便声明类型,不用写死,而是在运行时确定

    decltype(&x) p; // p的类型是int*
    cout << typeid(ret).name() << endl;
    cout << typeid(p).name() << endl;

    F(1, 'a');
    return 0;
}

补充:关于nullptr与范围for,参考之前这篇《初识C++(4)》


完~

未经作者同意禁止转载

你可能感兴趣的:(Cpp,c++,开发语言)