继承期间受保护成员的皮条

pimpl for protected member during inheritance

本文关键字:成员 受保护 继承      更新时间:2023-10-16

我有大量受保护的成员函数,这些函数在`基类hpp文件中声明,该文件由派生的类使用。我的想法是将它们从头文件中删除,以减少编译依赖性。我也想过对受保护的成员使用皮条客方法。

我在Base类cpp文件中定义了一个Impl类,并将所有受保护的函数移动到Impl类中。此外,我将Base类头文件中的Impl类正向声明为受保护成员。

protected:
class Impl;
Impl* impl_;

但在这样做的过程中,当我从派生的类中使用impl_调用受保护函数时,在派生类编译中发生了以下错误::

error: invalid use of incomplete type ‘class Base::Impl’
if (false == impl_->EncodeMMMsgHeader(mm_msg_header_)) {
error: forward declaration of ‘class Base::Impl’

我认为出现这个错误是因为在编译器需要有关类的上下文信息的任何情况下都不能使用正向声明,编译器只告诉它一点点关于类的信息也没有任何用处。

有什么办法可以克服上述问题吗?如果没有,那么有人能给我一个更好的方法来实现我的目标吗。

您可以添加一个层来减少依赖关系:

来自

#include "lot_of_dependencies"
#include <memory>
class MyClass
{
public:
~MyClass();
/*...*/
protected:
/* Protected stuff */
private:
struct Pimpl;
std::unique_ptr<Pimpl> impl;
};

添加

MyClassProtectedStuff.h

#include "lot_of_dependencies"
class MyClassProtectedStuff
{
public:
/* Protected stuff of MyClass */
private:
// MyClass* owner; // Possibly back pointer
};

然后

MyClass.h

#include <memory>
class MyClassProtectedStuff;
class MyClass
{
public:
~MyClass();
/*...*/
protected:
const MyClassProtectedStuff& GetProtected() const;
MyClassProtectedStuff& GetProtected();
private:
struct Pimpl;
std::unique_ptr<Pimpl> impl;
std::unique_ptr<MyClassProtectedStuff> protectedData; // Might be in Piml.
};

然后派生类应该包括这两个头,而常规类只包括MyClass.h