//初始化列表
int i_arr[3] = { 1, 2, 3 }; //普通数组
struct A
{
int x;
struct B
{
int i;
int j;
} b;
} a = { 1, { 2, 3 } }; //POD类型
//拷贝初始化(copy-initialization)
int i = 0;
class Foo
{
public:
Foo(int) {}
} foo = 123; //需要拷贝构造函数
//直接初始化(direct-initialization)
int j(0);
Foo bar(123);
这些不同的初始化方法,都有各自的适用范围和作用。最关键的是,这些种类繁多的初始化方法,没有一种可以通用所有情况。POD 类型即 plain old data 类型,简单来说,是可以直接使用 memcpy 复制的对象。
int i_arr[3] = { 1, 2, 3 };
long l_arr[] = { 1, 3, 2, 4 };
struct A
{
int x;
int y;
} a = { 1, 2 };
但是这种初始化方式的适用性非常狭窄,只有上面提到的这两种数据类型可以使用初始化列表。
class Foo
{
public:
Foo(int) {}
private:
Foo(const Foo &);
};
int main(void)
{
Foo a1(123);
Foo a2 = 123; //error: 'Foo::Foo(const Foo &)' is private
Foo a3 = { 123 };
Foo a4 { 123 };
int a5 = { 3 };
int a6 { 3 };
return 0;
}
在上例中,a3、a4 使用了新的初始化方式来初始化对象,效果如同 a1 的直接初始化。
int i_arr[3] { 1, 2, 3 }; //普通数组
struct A
{
int x;
struct B
{
int i;
int j;
} b;
} a { 1, { 2, 3 } }; //POD类型
在初始化时,{}前面的等于号是否书写对初始化行为没有影响。
int* a = new int { 123 };
double b = double { 12.12 };
int* arr = new int[3] { 1, 2, 3 };
struct Foo
{
Foo(int, double) {}
};
Foo func(void)
{
return { 123, 321.0 };
}
这里的 return 语句就如同返回了一个 Foo(123, 321.0)。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有