这是第六天的学习
1 #include <iostream>
2
3 using namespace std;
4
5 class A
6 {
7 private:
8 int num = 10;
9 public:
10 A() { cout << " This is A constructor. " << endl; }
11 ~A() { cout << " This is A deconstructor. " << endl; }
12 // void showInfo() { cout << " A number is " << this->num << endl; }
13 virtual void showInfo() { cout << " A number is " << this->num << endl; }
14 int getNum() { return this->num; }
15 };
16 class B : public A
17 // class B : protected A // 只能在子类中访问,类外无法访问
18 {
19 private:
20 int age;
21 int num = 100;
22 public:
23 B() { cout << " This is B constructor. " << endl; }
24 ~B() { cout << " This is B deconstructor. " << endl; }
25 void showInfo() { cout << " B age is " << this->age << endl; }
26 };
27 class C
28 {
29 public:
30 void func(A& a) { a.showInfo(); }
31 };
32
33 int main()
34 {
35 // -1类的继承(public,private,protected),提高代码的复用性和拓展性
36 // 单继承---> class 子类:继承方式 父类的类名 {子类的类体}
37 // 多继承---> class 子类:继承方式1 父类的类名1,继承方式2 父类的类名2,... {子类的类体}
38 // 继承发生时父子类之间的构造调用顺序,父类A先构造,子类B再构造;子类B先析构,父类B后析构.
39 //B b;
40
41 // 子类可以直接访问父类中的函数
42 // 同名函数被编译器隐藏在父类的作用域中
43 B* b = new B;
44 b->showInfo();
45 b->A::showInfo();
46
47 // 避免以下这样的情况,返回值为父类的num
48 cout << " b number is " << b->getNum() << endl;
49 cout << "------------" << endl;
50
51 // -2-类型的转换
52 // A* a = new B;
53 ((A*)b)->showInfo();
54 cout << ((A*)b)->getNum() << endl;
55 cout << "------------" << endl;
56
57 // 用父类的指针或引用去访问子类中的函数或属性是不安全的
58 // 子类对象可以转换为父类对象
59 B* b1 = (B*)(new A);
60 b1->showInfo(); // 调用A类中的函数
61 cout << "------------" << endl;
62
63 //
64 A a3;
65 B b3;
66 C c3;
67 c3.func(a3);
68 c3.func(b3); // 在父子类中存在同名函数时,只会调用父类的同名函数
69 // 在父类同名函数前加 virtual
70
71 //delete b;
72
73 //cout << "Hello World!" << endl;
74 return 0;
75 }