
class SomelibraryClass { public: SomelibraryClass() { /* start initialization */ } voID addFoo() { /* we are a collection of foos */ } voID funcToCallAfterallAddFoos() { /* Making sure this is called is the issue */ }};class SomeUserClass : public SomelibraryClass { public: SomeUserClass() { addFoo(); addFoo(); addFoo(); // SomeUserClass has three foos. }};class SomeUserDerrivedClass : public SomeUserClass { public: SomeUserDerrivedClass() { addFoo(); // This one has four foos. }}; 所以,我真正想要的是SomelibraryClass在构造过程结束时强制执行funcToCallAfterallAddFoos的调用.用户不能将它放在SomeUserClass :: SomeUserClass()的末尾,这会弄乱SomeUserDerrivedClass.如果他把它放在SomeUserDerrivedClass的末尾,那么它永远不会被SomeUserClass调用.
为了进一步说明我的需要,想象一下/ * start initialization * /获取一个锁,funcToCallAfterallAddFoos()释放一个锁.
编译器知道对象的所有初始化何时完成,但是我可以通过一些不错的技巧获取该信息吗?
解决方法 我可能会用某种工厂来实现它.以下代码应该被读作伪代码,我还没有尝试编译它或任何东西.class libraryClass{public: template<typename D> static D *GetNewInstance() { // by assigning the new D to a libraryClass pointer,you guarantee it derives from libraryClass at compile time // that way,the user can't accIDentally type "libraryClass::GetNewInstance<int>()" and have it work libraryClass *c = new D(); c->funcToCallAfterallAddFoos(); return c; } ...}; 总结 以上是内存溢出为你收集整理的c – 如何在派生类构造函数之后强制调用基类函数?全部内容,希望文章能够帮你解决c – 如何在派生类构造函数之后强制调用基类函数?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)