【发布时间】:2021-01-16 15:56:18
【问题描述】:
让我把问题说得更具体一些。我的问题是我有一个基类要发送给客户,以便客户可以在他们的末端开发派生类。如何隐藏私有方法和成员?
例如,在以下代码 sn-ps 中,base.h 文件声明了基类,该基类提供了三个私有虚拟方法供客户端在派生类中覆盖。客户端可以不覆盖任何一个或全部。假设客户开发了一个名为“Derived”的派生类,并将“派生”类创建者传递给我,以便我可以在某处创建派生类,例如Base* p_base = new Derived() 并调用 p_base->Execute() 以实际调用虚函数 DoInitialize()、DoExecute()、DoCleanUp() 的客户端实现。
顺便说一句:我不认为不透明的指针会起作用。
在 Base.h 文件中:
class Base {
public:
Base();
~Base();
void Execute();
private:
// virtual functions to be overridden by derived classes.
virtual void DoInitialize() {}
virtual void DoExecute() {}
virtual void DoCleanUp() {}
private:
// private members and functions that are intended to hide from clients
std::vector<float> data_;
....
}
在 Base.cpp 文件中
Base::Execute() {
DoInitialize();
DoExecute();
DoCleanUp();
}
在客户端
class Derived : public Base {
public:
Derived();
~Derived();
private:
// overide base class methods
void DoInitialize() {}
void DoExecute() {}
void DoCleanUp() {}
}
在我的尽头:
void main() {
Base* p = DerivedCreater(); // creater a Derived class, assumes DerivedCreater() has passed in by clients.
p->Execute(); // I want to call the client implementation of DoInitialize(), DoExecute(), and DoCleanUp()
}
【问题讨论】:
-
我相信 PIMPL 是最好的选择。我没有重新发布链接,因为它是同一主题的另一个问题中的第一个链接。
-
不透明的
m_impl指向实现的指针,其中m_impl知道Base并调用它的虚函数。 -
我必须重申我的问题并重新发布,因为我之前帖子中的答案完全搞砸了。通常这意味着两个问题之一将作为另一个副本关闭。
-
您可能对此感兴趣:Template Method Design Pattern.
-
@Ted Lyngmo,更广泛的范围是我们将在后台为 DoExecute() 提供数据输入,用户将实现 DoExecute() 任何他们想要处理的数据。 DoInitialize() 和 DoCleanUp() 实际上是在 Base::Execute() 之外执行的,但在这里我只想简单地问一个问题。