参考:
https://www.cnblogs.com/dong1/p/10700583.html
初始化列表语法:
#include <iostream>
#include <vector>
//结论:c++11支持列表初始化语句,这个语句的实际执行效果为:调用匹配参数列表的构造函数.
// c++99无法在构建实例时就对成员变量做初始化
class A {
public:
A() = default;
//注意:下面两个构造函数都是2个入参的,所以不能共存,所以只能写其中一种,根据具体业务需要判断,通常
// 需要给成员函数值得情况下都是使用 c++ 11版本
//A(int tmpi, char tmpc) { i = tmpi; c = tmpc; } //c++ 99 的方案 , 对比初始化列表的方案,先构造再复制要进行两个步骤,一是慢,二是不安全
A(int tmpi, char tmpc) :i(tmpi), c(tmpc) { ; } //c++ 11 初始化列表构造函数
//A(int tmpi, char tmpc) { ; } //如果不给成员变量赋值/初始化,初始化列表语句是不会自动给初值的,即是用这个构造函数
//配合初始化列表语句会导致成员变量值随机
~A() = default;
public:
void setI(int tmp) {
i = tmp;
}
void setC(char tmp) {
c = tmp;
}
public:
int i;
char c;
};
int main()
{
//c++ 99
//不能对非基础类型初始化,只能对基础类型初始化,比如 int array[10] = {1,2,3,4,5,6};
//因此如果初始化一个类,有两种途径: 1)先创建实例,然后再给成员变量赋值
// 2)创建包含成员变量的构造函数
//c++ 99 甚至都不支持初始化列表构造函数,编译器只能先创建对象,然后进入构造函数执行赋值语句
A a[2];
a[0].setI(10);
a[0].setC('c');
a[1].setI(11);
a[1].setC('d');
//c++ 11
A a_1[2] = { {20,'h'},{21,'i'} }; //使用初始化列表构造,要求A 必须有2个参数参数列表的构造函数
A a_2[2] = { A(30,'X'),A(31,'Z') }; //同上
std::vector<A> A_vector{ {40,'j'},{50,'k'} }; //容器也支持
std::cout << a_1[0].i;
std::cout << "Hello World!\n";
int i;
std::cin >> i;
}
auto即decltype:
#include <iostream>
#include <vector>
//小结:一般都用在复杂的类类型中,比如迭代器,嵌套容器类型 等等
int main()
{
int i=100;
float f=100.1;
auto v_auto = i + f; //定义变量来存放i + f的结果,具体的类型不管,由编译器来判断
decltype(i * f) v_auto_1; //定义类型为i*f结果类型的变量 v_auto_1
std::cout << sizeof(v_auto_1);
std::cout << "Hello World!\n";
int i;
std::cin >> i;
}
其他资料:
https://blog.csdn.net/aixintianshideshouhu/article/details/94548940