简体   繁体   English

C ++ - 基类和私有头

[英]C++ - Base class and private header

I'm writing a library in C++ and have a class hierarchy like this: 我正在用C ++编写一个库,并且有一个像这样的类层次结构:

message.h file (in ./mylib/src) message.h文件(在./mylib/src中)

class Message
{
};

request.h file (in ./mylib/include/mylib) request.h文件(在./mylib/include/mylib中)

#include "message.h"

class Request : public Message
{
};

response.h file (in ./mylib/include/mylib) response.h文件(在./mylib/include/mylib中)

#include "message.h"

class Response : public Message
{
};

I want everything in my mylib/src folder to be hidden from user and want only to distrubute files in mylib/include. 我希望我的mylib / src文件夹中的所有内容都对用户隐藏,并且只想在mylib / include中分发文件。 But the problem is as both requst.h and response.h #include message.h so user will get a "No such file" error when #including request.h and response.h. 但问题是requst.h和response.h #include message.h,因此当#including request.h和response.h时,用户将收到“No such file”错误。 Is there a way to work around this problem? 有办法解决这个问题吗?

You can simply provide a public interface for Message and keep the actual class hidden: 您可以简单地为Message提供公共接口并隐藏实际类:

class IMessage
{
    Message* pImpl;
};

Distribute this header and use a forward declaration for Message . 分发此标头并使用Message的前向声明。

Another option would be to use composition instead of inheritance (you'll need pointers as members, not the full object). 另一种选择是使用组合而不是继承(你需要指针作为成员,而不是完整的对象)。

If you want to be able to use Response and Request you need to include the header files where they are declared. 如果您希望能够使用ResponseRequest ,则需要将头文件包含在声明它们的位置。 That is why you should put those headers in the public include folder. 这就是为什么你应该把这些标题放在公共包含文件夹中。

基类应该公开分发,否则你将不得不编写序列化/反序列化的机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM