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. 自定义的拷贝赋值运算符函数,也不会调用基类的相应函数。