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) { 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();
} 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; }
|