在构建之后立即调用虚方法 [英] Call virtual method immediately after construction
本文介绍了在构建之后立即调用虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在构造派生对象之后,为给定的基本类派生的所有类调用一个虚方法。但是在基类构造函数中这样做会导致纯虚拟方法调用
I need to call a virtual method for all classes derived from a given base base class right after the construction of the derived object. But doing so in the base class constructor will result in a pure virtual method call
这是一个简化的示例:
struct Loader {
int get(int index) { return 0; }
};
struct Base{
Base() {
Loader l;
load( l ); // <-- pure virtual call!
}
virtual void load( Loader & ) = 0;
};
struct Derived: public Base {
int value;
void load( Loader &l ) {
value = Loader.get(0);
}
};
我可以通过加载
c $ c> Derived 构造函数,但 Derived
无法知道如何创建Loader。任何想法/解决方法?
I can call load
at the Derived
constructor, but Derived
could not know how to create a Loader. Any ideas/workarounds?
推荐答案
使用PIMPL模式:
template<typename T>
class Pimpl
{
public:
Pimpl()
{
// At this point the object you have created is fully constructed.
// So now you can call the virtual method on it.
object.load();
}
T* operator->()
{
// Use the pointer notation to get access to your object
// and its members.
return &object;
}
private:
T object; // Not technically a pointer
// But otherwise the pattern is the same.
// Modify to your needs.
};
int main()
{
Pimpl<Derived> x;
x->doStuff();
}
这篇关于在构建之后立即调用虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文