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. 編譯器會默認調用基類的構造函數。
2. 繼承類的拷貝構造函數/拷貝賦值運算符函數沒有定義,編譯器會默認調用基類相應的函數。
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. 拷貝構造函數會默認調用基類的構造函數,而不是對應的拷貝構造函數,除非在自己手動調用。
2. 自定義的拷貝賦值運算符函數,也不會調用基類的相應函數。