gpt4 book ai didi

c++ - C++中的API设计

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:30 24 4
gpt4 key购买 nike

我开始用 C++ 编写一个复杂的软件体,它使用了其他几个库,我现在担心的是我只希望有限数量的类可以访问这些库,但 C++ 头文件和对象包括 header 还应该可以访问类依赖项。最合适的解决方法是什么?

最佳答案

一个建议是使用 pimpl 或抽象“接口(interface)”模式。

pimpl 模式是您存储指向前向声明的实现类的指针的地方。

例子:


blah.hpp

class foo
{
struct impl;
impl* myImpl;
public:
foo();
}

blah.cpp

#incldue <internalClass>
struct foo::impl
{
internalClass o;
};

foo::foo()
{
myImpl = new impl();
}

另一种选择是拥有一个纯虚拟抽象类(也称为接口(interface))。然后你有一个工厂函数(或工厂类)返回一个指向你的实现的指针。因此,客户端代码永远不必在您的实现中看到成员。

例子:


inter.hpp

class inter
{
virtual void doFoo() = 0;
inter* create();
};

realInter.hpp

class realInter: public inter
{
virtual void doFoo() { //blah blah blah}
internalClass aMember;
};

inter.cpp

#include <realInter.hpp>
inter* inter::create()
{
return new realInter();
}

关于c++ - C++中的API设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9612781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com