加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何在派生类构造函数之后强制调用基类函数?

发布时间:2020-12-16 10:39:30 所属栏目:百科 来源:网络整理
导读:我正在为以下情况寻找一个干净的C语言: class SomeLibraryClass { public: SomeLibraryClass() { /* start initialization */ } void addFoo() { /* we are a collection of foos */ } void funcToCallAfterAllAddFoos() { /* Making sure this is called i
我正在为以下情况寻找一个干净的C语言:

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;
   }

   ...
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读