Cpp_part6

Cpp_part6

Charles Lv7

Cpp_part6

1.inheritance 继承

延伸类,子类

1
2
3
4
5
6
7
8
9
10
class Base {
int i;

public:
Base();
Base(int ai);
};
Base::Base(int ai) {
this->i = ai;
}

写该函数必须保留父类默认构造,否则创建子类时会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Base::Base() {
cout << "construct Base" << endl;
}
class Derived : public Base {
int j;

public:
Derived();
Derived(int ai, int aj);
};
Derived::Derived() {
cout << "construct Derived" << endl;
}
Derived::Derived(int ai, int aj) : Base(ai) {
this->j = aj;
cout << "construct Derived" << endl;
}
void test01() {
Derived d;
//构建子类对象会调用父类构造函数,先父后子,析构函数同理(先子后父)
cout << sizeof(Derived) << endl;
}
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
39
40
41
class Engine {
int i;

public:
Engine();
Engine(int ai);
};
Engine::Engine() {
cout << "construct Engine" << endl;
}
Engine::Engine(int ai) {
this->i = ai;
cout << "construct Engine" << endl;
}
class Car {
Engine e;
int j;
int k;

public:
Car();
Car(int m);
Car(int ai, int aj);
};
Car::Car(int m) : j(m), k(j) {
//按照变量定义顺序初始化,即k(m),j(k)会出现j为垃圾数的情况
cout << "test Car" << endl;
cout << "j:" << j << endl;
cout << "k:" << k << endl;
}
Car::Car() : e(1) {
cout << "construct Car" << endl;
}
Car::Car(int ai, int aj) : e(ai) {
this->j = aj;
cout << "construct Car" << endl;
}
void test02() {
Car c;
Car d(2);
}

2.Polymorphic 多态

多态 Polymorphic:简单而言一行函数可能在不同情况调用不同的代码

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Pet {
int i;

public:
virtual void speak(); //虚函数
virtual void sleep();
};
void Pet::speak() {
cout << "Pet::speak" << endl;
}
void Pet::sleep() {
cout << "Pet::sleep" << endl;
}
// 函数名是函数的首指针
class Cat : public Pet {
public:
void speak();
};
void Cat::speak() {
cout << "miao miao" << endl;
}
class Dog : public Pet {
public:
void speak();
};
void Dog::speak() {
cout << "wang wang" << endl;
}
void handle(Pet& pet) {
pet.speak();
// binding:绑定,将一次函数调用与函数入口相对应的过程
// early binding
// later binding(runtime binding,dynamic binding)[多态]
// v-table 虚函数表
// v-ptr 虚指针

/*
// 代码区:函数(代码),常量,lib
// 全局变量区
// runtime memory:
// 1.stack 2.heap
*/
}
void test03() {
Cat c;
c.speak();
handle(c);
Dog d;
d.speak();
handle(d);
//子类继承关系不要削弱父类的接口
cout << sizeof(Pet) << endl;
Cat c1, c2;
int* p = (int*)&c1;
cout << *p << endl;
p = (int*)&c2;
cout << *p << endl;
}

Main part

1
2
3
4
5
6
7
8
#include <bits/stdc++.h>
using namespace std;
int main() {
test01();
test02();
test03();
return 0;
}
  • Title: Cpp_part6
  • Author: Charles
  • Created at : 2022-12-28 08:33:58
  • Updated at : 2023-02-09 17:57:19
  • Link: https://charles2530.github.io/2022/12/28/cpp-part6/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments