在C ++头文件中使用第三方类 [英] Using third party classes in a C++ header file

查看:202
本文介绍了在C ++头文件中使用第三方类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有第三方类名为(包括命名空间) other :: OtherClass

Suppose there's a third party class named (including namespace) other::OtherClass.

头文件。

class MyClass {
  public:
    ...
  private:
    other::OtherClass other_class_;
    ...
}

如果此头文件在生产中发货,这将被视为将实现暴露给客户端吗?

If this header file was shipped in production, would this be considered exposing the implementation to the client?

另一方面,在公共接口中使用第三方类是否是个好主意? (注意,第二个示例不一定将该类保存为私有成员。)

On the other hand, is it a good idea or not to use a third party class in a public interface? (Note that this second example doesn't necessarily save that class into a private member.)

class MyClass {
  public:
    MyClass(const other::OtherClass& other_class);
    ...
  private:
    ...
}


$ b b

在第一个例子中,客户端必须知道 other :: OtherClass 的大小,并包含头文件。在第二个例子中,客户端需要能够构造 other :: OtherClass ,如果没有提供工厂,还可以 需要头文件。

In the first example, the client has to know the size of other::OtherClass and include the header file. In the second example, the client needs to be able to construct other::OtherClass which also might need the header file if a factory was not provided.

在做任何上述例子时有很好的借口吗?

Are there good excuses in doing any of the examples above?

如果这几乎从来不是一个好主意,那么设计上述类的常用方法是什么?

If this is almost never a good idea, what is the usual way to design classes like above?

推荐答案

供应商必须通过其提供的头文件向客户端公开一些的库。

Vendors have to expose some amount of their library to clients through the header files they provide.

话虽如此,有一些技术用于在实现中隐藏数据和函数。一个更常见的技术是提供公共代理类和工厂函数,只向客户端公开最小量的公共功能。

That being said, there are techniques for hiding data and functions within an implementation. One of the more common techniques is to provide public proxy classes and factory functions, which expose only a mimimal amount of public functionality to clients.

至于你的第二个问题,更好地使用头文件中的第三方类型的引用和指针,因为您可以将头文件中的类型转发声明为:

As to your second question, it's better to use references and pointers to the third-party types in your headers, since you can forward-declare the types within your header file as:

class other::OtherClass;

需要实际包含第三方头文件。这不会向您的图书馆客户提供任何第三方详细信息。

within needing to actually include the third-party header files. This does not expose any of the third-party details to clients of your libraries.

这篇关于在C ++头文件中使用第三方类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆