【发布时间】:2013-08-18 07:12:26
【问题描述】:
我想使用 pimpl idiom 创建一个类库,这样我就可以为库的用户隐藏我的实现细节。
是否有可能创建一个类,其中一些方法是公共的并且从用户的角度来看是可调用的,同时具有只能从内部调用的方法。
现在我只看到一个使用friend关键字并将内部方法声明为私有的解决方案。
例如: MyPartiallyVisibleClass:包含用户可访问的混合方法的类,以及仅可访问库内部的方法。 InternalClass:库内部的类。用户永远不会知道这个存在。
// MyPartiallyVisibleClass.h: Will be included by the user.
class MyPartiallyVisibleClass
{
private:
class Impl; // Forward declare the implementation
Impl* pimpl;
InternalMethod(); // Can only be called from within the library-internals.
public:
UserMethod(); // Will be visible and callable from users perspective.
}
// MyPartiallyVisibleClass.cpp
class MyPartiallyVisibleClass::Impl
{
private:
InternalMethod();
public:
UserMethod();
friend class InternalClass;
}
// Internal class that will not be included into users application.
class InternalClass
{
public:
InternalMethod()
{
MyPartiallyVisibleClass pvc;
pvc.InternalMethod();
}
}
有更好的方法吗?
【问题讨论】:
-
你为什么需要它?最简单的方法是只将公共方法放在用户类中,并将所有血淋淋的细节留给实现。
-
不是重复的:这个问题更具体。除非考虑到每个关于 pimpl 的问题都是重复的......
-
我认为这里的所有内容都包含在该帖子中。 :) 这些话题一次又一次地被过度讨论。除了一般原则之外,我在这里没有看到任何具体内容。
标签: c++ pimpl-idiom