Item 7区分使用 () 和{}创建对象
1. 基本数据类型
1
2
3
4
5
6
7
|
void BaseTypeUse()
{
int x(0);
int y=0;
int z{0};
int z2={0};
}
|
2.标准库的数据类型
1
2
3
4
5
6
7
8
|
void VectorUse()
{
std::vector<int> v{1,3,4,5};
std::map<int,std::string> m{
{1,"ok"},
{2,"over"}
};
}
|
3.类的成员变量
1
2
3
4
5
6
7
8
|
class Widget
{
private:
int x{0};
int y=0;
//int z(0);//Compiler Error
};
|
4.没有使用std::initializer_list
的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class WidgetBase
{
public:
WidgetBase()
{
std::cout<< __LINE__ <<"Default No Param constructor" << std::endl;
}
WidgetBase(int x,double y)
{
std::cout << __LINE__ << "One Int One Double Constructor"<< std::endl;
}
WidgetBase(int x,bool y)
{
std::cout << __LINE__ <<"one Int One bool Contructor" << std::endl;
}
WidgetBase(const WidgetBase& other){
std::cout << "Copy Constructor" << std::endl;
}
WidgetBase operator = (const WidgetBase& other){
std::cout << "Equal Constructor" << std::endl;
}
private:
int x{0};
int y=0;
//int z(0);//Compiler Error
};
WidgetBase w9(10,true);
WidgetBase w10{10,true};
WidgetBase w11(10,5.0);
WidgetBase w12{10,5.0};
|
5.使用了std::initializer_list
的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
class Widget
{
public:
Widget()
{
std::cout << __LINE__ << "Default No Param constructor"<< std::endl;
}
Widget(int x)
{
std::cout << __LINE__ << "One Int Param constructor" <<std::endl;
}
Widget(int x,double y)
{
std::cout << __LINE__ << "One Int One Double Constructor" << std::endl;
}
Widget(int x,bool y)
{
std::cout << __LINE__<< "one Int One bool Contructor" << std::endl;
}
Widget(std::initializer_list long double> il)
{
std::cout << __LINE__ << "std::initializer long double Constructor" << std::endl;
}
Widget(const Widget& other){
std::cout << "Copy Constructor" << std::endl;
}
Widget operator = (const Widget& other){
std::cout << "Equal Constructor" << std::endl;
}
operator float () const{
std::cout << "operator float" <<std::endl;
return 0.0;
}
private:
int x{0};
int y=0;
//int z(0);//Compiler Error
};
Widget w;
Widget w2=w;
w=w2;
Widget w3{};
Widget w4();
Widget w5(10,true);
Widget w6{10,true};
Widget w7(10,5.0);
Widget w8{10,5.0};
Widget w81{10,5.0};
Widget w82{w81};
Widget w83(w82);
|
总结
对于基本类型的初始化,()
和 {}
的区别不大.
使用{}
能更方便的对标准模板库进行初始化.
类的成员变量可以使用 {}
和 =
进行初始化,但是不能使用 ()
.
对于不含有std::initializer_list
为参数的构造函数来说,使用()
和{}
构造对象的方式基本相同.
对于含有std::initializer_list
为参数的构造函数的对象来说,()
使用默认的构造函数,{}
优先使用 std::initializer_list
为参数的构造函数.