美文网首页
简单接口封装

简单接口封装

作者: 愿时光温柔待她 | 来源:发表于2018-11-22 16:23 被阅读0次

    细节隐藏,对外只透出一个头文件和一个函数!

    1. main.cpp

    #include <iostream>
    #include "animal.hpp"
    
    int main()
    
    {
        Animal*cnt_1 =create();
        cnt_1->run();//Tiger is running !!!
        return 0;
    }
    

    对外只透出animal.hpp 文件,其他封装,细节隐藏!

    2. animal.hpp

    #ifndef animal_hpp
    #define animal_hpp
    
    #include <stdio.h>
    class Animal
    {
    public:
        virtual void run() = 0;
    };
    
    Animal* create();
    
    #endif /* animal_hpp */
    

    以下内容编译生成库文件,存在lib文件夹下,不对外透出!

    3. animal.cpp

    #include "animal.hpp"
    #include "tiger.hpp"
    
    Animal* create()
    {
        return new Tiger;
    }
    

    4. tiger.hpp

    #ifndef tiger_hpp
    #define tiger_hpp
    
    #include <stdio.h>
    #include "animal.hpp"
    
    class Tiger: public Animal
    {
        
    public:
        void run();
    };
    #endif /* tiger_hpp */
    
    

    4. tiger.cpp

    #include "tiger.hpp"
    #include <iostream>
    
    void Tiger::run()
    {
            std::cout << "Tiger is running !!!" << std::endl;
    }
    
    

    相关文章

      网友评论

          本文标题:简单接口封装

          本文链接:https://www.haomeiwen.com/subject/ulwlqqtx.html