我能以某种方式使用继承吗
Can I use inheritance this way somehow
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} }
{
}
这两种解决方案都有各自的缺点,最值得注意的是,实现不在派生类中,因此您必须考虑如何解决范围界定问题(例如,在实现中访问派生类的私有成员)。
相关文章:
- 为什么C++需要公共继承,忽略朋友声明,才能使动态向下工作?
- 如何以编程方式使窗口全屏显示?
- 以编程方式防止重命名或删除文件,但仍使其可写
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 如何使 printf 以与 NSLog 相同的方式打印字符缓冲区?
- 如何使模板化类保留继承?
- 使从一个基类派生的类能够使用继承的受保护成员
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 模板类的专门继承使成员函数返回模板类型,而不是继承的类类型
- 如何使继承的类与父类仅在C++中的一个值不同
- C++多重继承 - 相同的方法名称 - 我可以以某种方式删除其中一个吗?
- 升级到以多种方式为基类的C 类(不必使用虚拟继承)
- 如何使用模板或继承使以下代码工作
- 如何使C 继承保护访问说明器
- 如何使继承相同基类的类的虚拟方法弄清楚如何处理它们的参数?
- 使代码变小以进行多重继承
- 继承,使基本成员变量const
- 告诉 PDCurses 以编程方式使窗口与物理屏幕大小相同的方法
- opencv函数的继承是否使我的程序变得更好
- 如何以编程方式使系统崩溃