我能以某种方式使用继承吗

Can I use inheritance this way somehow

本文关键字:继承 方式使      更新时间:2023-10-16

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

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

这就是我的想法。在我实际使用的情况下,有大量的虚拟函数我可能会与任何函数一起使用,我不想让类声明与所有额外的函数纠缠在一起。

这在纯继承/虚拟函数中是不可能的,但您可以注入函数的实现:

// 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 }
{
}

你可以用皮条客这个成语来达到同样的目的。这避免了每个方法都有一个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} }
{
}

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