【问题标题】:pimpl for protected member during inheritance继承期间受保护成员的 pimpl
【发布时间】:2018-12-27 10:14:54
【问题描述】:

我有大量的 protected 成员函数在 派生 类使用的`基类 hpp 文件中声明。我的想法是从头文件中删除它们以减少编译依赖。我也想过对受保护的成员使用 pimpl 方法。

我在 Base 类 cpp 文件中定义了一个 Impl 类,并将所有 protected 函数移到 Impl 中班级。此外,我在 Base 类头文件中将 Impl 类作为受保护成员进行了前向声明。

protected:
    class Impl;
    Impl* impl_;

但这样做时,当我使用 derived 类中的 impl_ 调用受保护函数时,派生类编译中出现以下错误::

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

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

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

【问题讨论】:

  • 受保护和虚拟方法是接口的一部分,不应隐藏在 pimpl 中。
  • 不确定@Jarod42,受保护的虚函数通常是实现的一部分,而几乎从不是接口的一部分。
  • @EduardRostomyan:派生类看到并可以使用protected 数据,并且可以覆盖每个virtual(非final)方法。
  • 同意,但这并不使它成为类接口的一部分,恰恰相反,它使它们成为实现的一部分

标签: c++ oop inheritance protected pimpl-idiom


【解决方案1】:

你可以添加一个层来减少依赖:

来自

#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

【讨论】:

  • 我还有另一个目的是从头文件中删除受保护的成员函数。因为我必须在不需要这些受保护内容的大量其他文件中包含“MyClass.h”头文件。虽然你的想法会很好,但它会破坏我上述同样重要的目的。
猜你喜欢
  • 2016-06-12
  • 2014-06-09
  • 2012-10-03
  • 2023-03-03
  • 2014-01-30
  • 1970-01-01
  • 2023-03-23
  • 2012-09-26
  • 2016-02-29
相关资源
最近更新 更多