在C++98/03中,可以使用初始串列对普通数组和POD类型的成员进行初始化。(注: POD指C风格的,纯数据(没有成员函数)构成的结构体(类),简单的说,就是可以直接使用 memcpy 进行复制的变量(对象))
int g_arr[3]={0,1,2};
struct A //POD type
{
int x;
int y;
};
A a={1,2};
在上面的示例中数组g_arr中的3个元素值分别为:0, 1,2;变量a的成员值为:a.x = 1, a.y = 2。虽然这种初始化的方法简单易懂,但是很不幸,在C++98/03中只能用于数组和POD类型!
在C++11中,初始串列的适用性被大大的增加了。
1) 基本类型
C++11中扩大了初始串列的使用范围,基本类型变量也能支持初始串列的方式。
示例:
int a1=1; //C++98/03
int a2=int(1); //C++98/03
int a3 (1); //C++98/03
int a4={1}; //C++11
int a5 {1}; //C++11
2) 类类型
C++11中也将初始串列应用于自定义类类型,下面的使用方式将触发构造函数被调用。
示例:
#include <iostream>
using namespace std;
class Foo
{
public:
Foo(int i)
{
cout << "Foo(int i):i=" <<i<< endl;
}
};
void main()
{
Foo f1(1); //C++98/03
Foo f2 = 2;//C++98/03
Foo f3 = {3}; //C++11
Foo f4{4}; //C++11
cin.get();
}
3) 动态内存分配时的初始化
初始串列的引入使得任何方式的动态内存分配都可以同时进行初始化。
示例:
#include <iostream>
using namespace std;
void main()
{
int* p1 = new int(1); //C++98/03
int* p2 = new int{2}; //C++11
int* p3 = new int[3]{3,2,1}; //C++11,动态在堆空间上申请3个整形的大小,然后初始化为3,2,1
//第三种初始化方式是不是和Java中一模一样的呢?的确是的,C++11已经非常像Java了
cout << "*p1=" << *p1 << endl;
cout << "*p2=" << *p2 << endl;
for (int i = 0; i < 3; i++)
{
cout << p3[i] << endl;
}
delete p1;
delete p2;
delete[] p3;
cin.get();
}
4) 新旧特性的冲突
下面的初始化结果是你期望的吗???
示例:
#include <iostream>
using namespace std;
struct B1
{
int i;
int j;
}b1 = { 1,2 };
struct B2
{
int i;
int j;
B2(int, int) :i(0), j(1)
{
}
}b2 = {1,2};
void main()
{
cout << b2.i << endl;
cout << b2.j << endl;
cin.get();
}
规则:
1.如果有对应的构造函数,优先调用构造函数
2.如果没有对应的构造函数,这使用传统的方式对成员逐个赋值
5) 函数返回时的应用
可以直接将一个初始串列作为变量(对象)返回。
示例:
#include <iostream>
using namespace std;
struct A
{
int x;
int y;
}a1 = {1,2};
A getD3(int i, int j)
{
return{i,j};
}
int getInt()
{
return {5};
}
void main()
{
struct A a = getD3(3,4);
cout << "a.x=" << a.x << endl;
cout << "a.y=" << a.y << endl;
int i = getInt();
cout << "i=" << i << endl;
cin.get();
}
由于返回值的类型已经申明;因此,返回语句中的初始串列能够被转化为对应的类型的变量(对象)。
6> C++11 中直接支持在类中定义成员变量的时候进行初始化,而在经典C++(98/03)中是不允许这样的初始化方式的,如下的代码所示。感觉是不是开发体验好了很多呢?
#include <iostream>
using namespace std;
class Test
{
public:
int a = 1;
int b = 2;
};
void main()
{
Test t;
cout << "t.a=" << t.a << endl;
cout << "t.b=" << t.b << endl;
cin.get();
}
输出:
t.a=1
t.b=2