多态的实现方式,继承与模版函数

stl,boost中几乎所有容器都采用的是模版类+模版算法的方式实现多态,因为其效率更高!究其原因,静态编译

/* 
 * File:   main.cpp
 * Author: Vicky.H
 *
 */
#include <iostream>

/**动物*/
class Animal {
public:

    virtual ~Animal() { };
    virtual void eat() = 0;
    virtual void sleep() = 0;
    virtual void breed() = 0;
};

/**哺乳动物*/
class Mammal : public Animal {
public:

    ~Mammal() {
        std::cout << "delete Mammal" << std::endl;
    }

    void eat() { }

    void sleep() { }

    void breed() {
        std::cout << "哺乳动物胎生繁殖" << std::endl;
    }

};

/**卵生动物*/
class Ovipara : public Animal {
public:

    ~Ovipara() {
        std::cout << "delete Ovipara" << std::endl;
    }

    void eat() { }

    void sleep() { }

    void breed() {
        std::cout << "卵生动物产卵繁殖" << std::endl;
    }
};

template <typename T>
void breed(T& o) {
    std::cout << "void breed(T& o)" << std::endl;
    o.breed();
}

template <typename T>
void breed(const T& o) { /**重点:: 这里如需要const特化的话,需要所有的成员函数以const修饰*/
    std::cout << "void breed(const T& o)" << std::endl;
    o.breed();
}

template <typename T>
void breed(T* p) {
    std::cout << "void breed(T* p)" << std::endl;
    p->breed();
}

template <typename T>
void breed(const T* p) {
    std::cout << "void breed(const T* p)" << std::endl;
    p->breed();
}

class A {
public:

    void breed() const {
        std::cout << "哺乳动物胎生繁殖" << std::endl;
    }
};

class B {
public:

    void breed() const {
        std::cout << "卵生动物产卵繁殖" << std::endl;
    }
};

/*
 * 
 */
int main(void) {

    Animal* a1 = new Mammal;
    a1->breed();

    Animal* a2 = new Ovipara;
    a2->breed();

    delete a1;
    delete a2;


    std::cout << "---------------------------" << std::endl;

    A a;
    const B b;
    breed(a);
    breed(b);

    breed(&a);
    breed(&b);
    


    std::cout << "可以使用继承方式创建逻辑结构,然后删除父类,将抽象函数定义对应的模版函数将继承方式转向模版方式,相对而言,模版采用静态时编译与多态的动态时编译性能更高" << std::endl;
    
    return 0;
}


 

你可能感兴趣的:(算法,File,delete,Class)