Cpp_part7
1.abstract class 抽象类
abstract class抽象类(第一类高级抽象)
抽象类的限制:
1.抽象类不能实例化
2.对子类的继承复用性仍然存在
3.抽象类的作用在于提纲挈领
4.纯虚函数通常没有函数体,但可以有函数体
5.抽象类的纯虚函数通常都重写,但可以不重写,但会无法实例化
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
| class Pet { int age;
public: virtual void speak() = 0; virtual void sleep() = 0; };
class Dog : public Pet { public: virtual void speak(); virtual void sleep(); }; void Dog::speak() { cout << "wang wang" << endl; } void Dog::sleep() { cout << "dog sleep" << endl; } void handle(Pet& pet) { pet.speak(); } void test01() { Dog dog; handle(dog); dog.sleep(); }
|
2.虚函数
虚函数
1.constructor是唯一的确认的调用,不会和多态产生关系
2.destructor大多与多态产生关系
3.串联(类似java的interface)(第二类高级抽象)
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 59 60 61 62 63 64 65
| class Test { public: Test(); virtual ~Test(); }; Test::Test() {} Test::~Test() { cout << "~Test" << endl; } class Derived : public Test { public: Derived(); ~Derived(); }; Derived::Derived() {} Derived::~Derived() { cout << "~Derived" << endl; } void fun(Test* p) { delete p; } void test02() { Dog dog; Dog* pdog = new Dog; Derived* p = new Derived; fun(p); } class Fly_object { public: virtual void fly() = 0; }; class Animal { public: void fly(); }; class Bird : public Animal, public Fly_object { public: void fly(); }; void Bird::fly() { cout << "Bird fly" << endl; } class Machine { public: void fly(); }; class Airplane : public Machine, public Fly_object { public: void fly(); }; void Airplane::fly() { cout << "Airplane fly" << endl; } void follow(Fly_object& f) { f.fly(); } void test03() { Bird b; Airplane a; follow(b); follow(a); }
|
3.template 模板
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
|
template <typename T> class Stack { T pool[100]; int top;
public: Stack(); T Pop(); void Push(T a); }; template <typename T> Stack<T>::Stack() : top(-1) {} template <typename T> T Stack<T>::Pop() { return pool[top--]; } template <typename T> void Stack<T>::Push(T a) { pool[++top] = a; } void test04() { Stack<int> s; for (int i = 0; i < 10; i++) { s.Push(i * i); } for (int i = 0; i < 10; i++) { cout << s.Pop() << endl; } Stack<double> ds; for (int i = 0; i < 10; i++) { ds.Push(i * i + 0.1); } for (int i = 0; i < 10; i++) { cout << ds.Pop() << endl; } }
|
STL:Standard Template Library 动态增长的万能容器
1 2 3 4 5 6 7 8 9 10
| void test05() { vector<int> v; for (int i = 0; i < 2000; i++) { v.push_back(i); } cout << v.size() << endl; v.pop_back(); cout << v.back() << endl; cout << v[200] << endl; }
|
Main part
1 2 3 4 5 6 7 8 9 10 11 12
| #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cout.tie(NULL); test01(); test02(); test03(); test04(); test05(); return 0; }
|