C++使用面向接口编程方式隐藏实现

2020-11-05  本文已影响0人  FredricZhu

工程结构


图片.png

main.cpp

#include "utils/utils.hpp"
using namespace utils;

int main() {
    PrintPtr ptr = CreatePrinter("1.log", "r");
    std::string s;
    int n;
    while((n=ptr->Print(s, utils::BUFFER_SIZE)) != utils::F_EOF) {
        std::cout << s;
    }
    std::cout << std::endl;
    system("pause");
    return 0;
}

utils.hpp

#include "printer.hpp"

namespace utils {
    typedef boost::shared_ptr<IPrinter> PrintPtr;
    static const int F_EOF = 0;
    static const int BUFFER_SIZE = 50;
    
    PrintPtr CreatePrinter(std::string name, std::string mode) {
        PrintPtr ptr(new Printer(name, mode));
        return ptr;
    }
};

printer.hpp

#ifndef PRINTER_HPP
#define PRINTER_HPP
#include <windows.h>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/format.hpp>

using namespace std;
using namespace boost;

namespace utils
{
    class IPrinter
    {
    public:
        virtual int Print(std::string &s, size_t size) = 0;

    protected: //受保护的虚拟析构函数,导致本类必须被继承,也不能调用Delete操作符
        virtual ~IPrinter()
        {
            std::cout << "Invoke IPrinter 虚析构函数" << std::endl;
        }
    };

    class Printer: public IPrinter {
        private:
            FILE* f;
        public:
            Printer(std::string name, std::string mode);
            int Print(std::string &s, size_t size);
            ~Printer();
    };
}; // namespace utils
#endif

printer.cpp

#include "printer.hpp"

utils::Printer::Printer(std::string name, std::string mode){
    f = fopen(name.c_str(), mode.c_str());
}

utils::Printer::~Printer() {
    int res = fclose(f);
    std::cout << "Invoke Printer类的析构函数 res= " << res << std::endl;
}

int utils::Printer::Print(std::string &s, size_t size) {
    char data[size+1];
    int res = fread(data, 1, size, f);
    data[size] = '\0';
    s = boost::str(boost::format(data));
    return res;
}

程序输出如下


图片.png
上一篇下一篇

猜你喜欢

热点阅读