c++ 对外提供头文件的模式

使用c++语言开发的程序,可以对外提供C语言形式的头文件,也可以提供C++语言形式的头文件。

提供C++语言形式的头文件时,我们不希望暴露太多的细节,因此,一般定义一个抽象接口,然后把这个接口头文件提供出去。

这个抽象接口还必须有一个静态的工厂函数,而这个工厂函数的具体实现也是在库里面实现。 通过这个工厂函数就可以将真正的

类对象创建出来,这个类对象是继承并实现了接口类的。

例:

1、接口文件

class interface
{
    public:
        static interface *create();
        virtual int add(int a, int b) = 0;
};

2、实现接口的类,里面同时也实现了工厂函数create。

 1 #include <interface.h>
 2 
 3 class interfaceimpl : public interface
 4 {
 5     public:
 6         int add(int a, int b)
 7         {
 8             return a+ b;
 9         }
10 };
11 
12 interface* interface::create()
13 {
14     return new interfaceimpl;
15 }

3、main函数测试

 1 #include <stdio.h>
 2 #include <interface.h>
 3 
 4 int main()
 5 {
 6     interface *in = interface::create();
 7     int c = in->add(2, 3);
 8     printf("c : %d
", c);
 9 
10     return 0;
11 }

如果是C++11的话,也完全可以使用智能指针包装一下,对外提供智能指针形式的抽象接口。 关键点还是在create工厂函数。

原文地址:https://www.cnblogs.com/wanmeishenghuo/p/14489638.html