Example1:
1 class A {
2 public:
3 A() {
4 std::cout << "A.ctor()" << std::endl;
5 }
6 A(const A& other) {
7 std::cout << "A.copyctor()" << std::endl;
8 }
9 A& operator =(const A& other) {
10 std::cout << "A.op =() " << std::endl;
11 }
12 };
13
14 class AA : public A
15 {
16 public:
17 AA() {
18 std::cout << "AA.ctor()" << std::endl;
19 }
20 };
21
22 int main()
23 {
24 AA aa; // A.ctor => AA.ctor
25 AA bb(aa); // A.copyctor
26 aa = bb; // A.op =
27 return 0;
28 }
29
1. 編譯器會默認(rèn)調(diào)用基類的構(gòu)造函數(shù)。
2. 繼承類的拷貝構(gòu)造函數(shù)/拷貝賦值運(yùn)算符函數(shù)沒有定義,編譯器會默認(rèn)調(diào)用基類相應(yīng)的函數(shù)。
Example2:
1 class A {
2 public:
3 A() {
4 std::cout << "A.ctor()" << std::endl;
5 }
6 A(const A& other) {
7 std::cout << "A.copyctor()" << std::endl;
8 }
9 A& operator =(const A& other) {
10 std::cout << "A.op =() " << std::endl;
11 }
12 };
13
14 class AA : public A
15 {
16 public:
17 AA() {
18 std::cout << "AA.ctor()" << std::endl;
19 }
20 AA(const AA& other)
21 : A(other) {
22 std::cout << "AA.copyctor() " << std::endl;
23 }
24 AA& operator =(const AA& other) {
25 std::cout << "AA.op =()" << std::endl;
26 }
27 };
28
29 int main()
30 {
31 AA aa; // A.ctor => AA.ctor
32 AA bb(aa); // A.copyctor => AA.copyctor
33 aa = bb; // AA.op =
34
35 return 0;
36 }
1. 拷貝構(gòu)造函數(shù)會默認(rèn)調(diào)用基類的構(gòu)造函數(shù),而不是對應(yīng)的拷貝構(gòu)造函數(shù),除非在自己手動調(diào)用。
2. 自定義的拷貝賦值運(yùn)算符函數(shù),也不會調(diào)用基類的相應(yīng)函數(shù)。