转自:
http://www.nowcoder.com/test/question/done?tid=419355&qid=15301#summary
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
|
# include <iostream>
using namespace std;
class
A
{
public
:
A() { cout<<
"create A"
<<endl; }
A(
const
A& other){ cout<<
"copy A"
<<endl;}
//复制构造函数
~A() { cout<<
"~A"
<<endl; }
};
class
C
{
public
:
C() { cout<<
"create C"
<<endl; }
C(
const
A& other){ cout<<
"copy C"
<<endl;}
//复制构造函数
~C() { cout<<
"~C"
<<endl; }
};
class
B:
public
A
{
public
:
B()
{
cout<<
"create B"
<<endl;
}
~B()
{
cout<<
"~B"
<<endl;
}
private
:
C _a;
};
int
main(
void
)
{
B b;
cout<<
"------------------------"
<<endl;
}
|
上面的输出结果为
create A
create C
create B
------------------------
~B
~C
~A
先构造父类A,再构造成员变量C,最后才是构造自己B
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
|
class
A
{
public
:
A() { }
~A() { cout<<
"~A"
<<endl; }
};
class
B:
public
A
{
public
:
B(A &a):_a(a)
{
}
~B()
{
cout<<
"~B"
<<endl;
}
private
:
A _a;
};
int
main(
void
)
{
A a;
//很简单,定义a的时候调用了一次构造函数
B b(a);
}
|
1 先构造 A ,2 再继承父类构造A,3 拷贝构造b的成员A _a , 4 在构造B
所以析构 ~B ~A ~A ~A