【问题标题】:Can I use inheritance this way somehow我可以以某种方式使用继承吗
【发布时间】:2014-08-30 11:32:48
【问题描述】:

您好,我想使用继承类的虚函数,而不必将其包含在最终会进入头文件的类原型中。有没有办法做到这一点?

class Base {
public:
    virtual void func () = 0;
};

class Derived : public Base {
public:

};

void Derived::func () {
return;
}

这就是我的想法。在我实际使用的情况下,我可能会在任何函数中使用大量的虚函数,并且我不想让所有额外的函数陷入类声明。

【问题讨论】:

  • 不,你无法避免。原因?你的头文件的用户(包括编译器)怎么会知道你的类是非抽象的?
  • 这是 C++ 最大的弱点之一。它导致编译速度慢得多。有一些解决方案可以减少这个问题,例如 pimpl idiom,但这仍然是问题。
  • @ikh:不清楚这个“问题”和编译速度有什么关系?
  • “我不想让类声明陷入困境......” - 听起来你不想让声明陷入类声明......;o)

标签: c++ inheritance virtual


【解决方案1】:

这对于普通的继承/虚函数是不可能的,但你可以注入你的 func 实现:

// header file

#include <functional>

class Base {
public:
    Base(std::function<void()> func_impl)
        : m_func_impl{ std::move(func_impl) }
    {
    }

    void func() { m_func_impl(); }

private:
    std::function<void()> m_func_impl;
};

class Derived : public Base {
public:
    Derived();
};

// implementation file

static void Derived_func()
{
    // your implementation of func
}

Derived::Derived()
    : Base{ Derived_func }
{
}

您可以通过使用 pimpl 习语来完成相同的操作。这避免了每个方法都有一个std::function,但需要一个辅助类层次结构:

// header file

#include <memory>

class Base {
public:
    struct Impl
    {
        virtual ~Impl() {}
        virtual void func() = 0;
    };

    Base(std::unique_ptr<Impl> impl)
        : m_impl{ std::move(impl) }
    {
    }

    void func() { m_impl->func(); }

private:
    std::unique_ptr<Impl> m_impl;
};

class Derived : public Base {
public:
    Derived();
};

// implementation file

class Derived_Impl : public Base::Impl
{
    virtual void func() override
    {
        // your implementation of func
    }
};

Derived::Derived()
    : Base{ std::unique_ptr < Impl > {new Derived_Impl} }
{
}

这两种解决方案都有其缺点,最明显的是实现不在派生类中,因此您必须考虑如何解决范围问题(例如,在您的实现中访问派生类的私有成员)。

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    相关资源
    最近更新 更多