代码
1 #include <iostream>
2 using namespace std;
3
4 class Base{
5 public:
6 explicit Base(int i=0):ival(i)
7 {
8 cout << "Class Base's constructure is called" << endl;
9 }
10 Base(const Base& b)
11 {
12 cout << "Class Base's copy constructure is called" << endl;
13 }
14 private:
15 int ival;
16 };
17
18 class Base1{
19 public:
20 Base1(int ival): mybase(ival)
21 {
22 cout << "Base1's constructure is called" << endl;
23 }
24 private:
25 Base mybase;
26 };
27
28 void fun(Base b)
29 {
30 cout << "fun is OK" << endl;
31 }
32
33 void main()
34 {
35 int val = 5;
36 Base1 base1(val);
37 cout << endl;
38 fun(Base(val));
39
40 int ival;
41 cin >> ival;
42 }
2 using namespace std;
3
4 class Base{
5 public:
6 explicit Base(int i=0):ival(i)
7 {
8 cout << "Class Base's constructure is called" << endl;
9 }
10 Base(const Base& b)
11 {
12 cout << "Class Base's copy constructure is called" << endl;
13 }
14 private:
15 int ival;
16 };
17
18 class Base1{
19 public:
20 Base1(int ival): mybase(ival)
21 {
22 cout << "Base1's constructure is called" << endl;
23 }
24 private:
25 Base mybase;
26 };
27
28 void fun(Base b)
29 {
30 cout << "fun is OK" << endl;
31 }
32
33 void main()
34 {
35 int val = 5;
36 Base1 base1(val);
37 cout << endl;
38 fun(Base(val));
39
40 int ival;
41 cin >> ival;
42 }
Base1的构造函数的成员初始化列表中,调用的是explicit的构造函数,注意不是copy构造函数。
如果Base的构造函数不声明为explicit,若想以int类型实参调用fun函数,则fun的形参必须为Base对象,为Base&则错误。
如果Base的构造函数为explicit,不可用int形参调用fun(Base b)。