您好,我想使用继承类的虚函数,而不必将其包含在最终会进入头文件的类原型(prototype)中。有什么办法吗?
class Base {
public:
virtual void func () = 0;
};
class Derived : public Base {
public:
};
void Derived::func () {
return;
}
我是这么想的。在我实际使用的情况下,有大量的虚函数我可能会与任何函数一起使用,我不想让所有额外函数的类声明陷入困境。
最佳答案
这对于简单的继承/虚函数是不可能的,但你可以注入(inject)你的 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} }
{
}
这两种解决方案都有其缺点,最明显的是实现不在派生类中,因此您必须考虑如何解决范围问题(例如,在您的实现中访问派生类的私有(private)成员)。
关于c++ - 我能以某种方式使用继承吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25581891/