静态库:从头文件隐藏私有成员 [英] Static library: hiding private members from header file

查看:58
本文介绍了静态库:从头文件隐藏私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将部分代码编译为静态库以包含在其他项目中.当然,我必须分发编译后的库和包含类声明和公共成员的头文件,但是我不知道是否可以将所有私有成员和声明移到与头文件不同的位置./p>

示例:

在project.h文件中:

  class MyClass{上市:我的课();void Give_me_an_input(int);int Get_your_output();私人的:整数a,b;int MySecretAlgorithm();}; 

在.cpp文件中:

  MyClass :: MyClass(){a = 1;b = 0;}无效的MyClass :: Give_me_an_input(int c){b = c;}int MyClass :: Get_your_output(){返回MySecretAlgorithm();}int MyClass :: MySecretAlgorithm(){返回(a + b);} 

是否可以将所有私有成员 int a,b; int MySecretAlgorithm(); 移至与头文件不同的位置?

解决方案

在这种情况下,通常使用 解决方案

The pointer to implementation idiom can be used in such a scenario, commonly referred to as pimpl. The basic idea is to take the implementation details out of the declaration and simply have an opaque pointer to the implementation details.

std::unique_ptr is used in the the following example; but you could of course just use normal pointers.

// my_class declaration unit.
class my_class {
private:
   class impl;
   unique_ptr<impl> pimpl;

public:

};

// my_class implementation unit
class my_class::impl {
   int whatever;
   int whenever;
};

my_class::my_class(): pimpl( new impl )
{
}

这篇关于静态库:从头文件隐藏私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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