This question already has answers here:
Why can't I dynamic_cast “sideways” during multiple inheritence?

(4个答案)


2年前关闭。




我的类使用接口(interface),并且如果在对象创建时使用了接口(interface),则需要信息:

界面:
class IServerSetup {
  public:
    virtual void ServerSetup () = 0;
}

类(class):
class MyServer : public MqC, public IServerSetup {
  public:
    MyServer(MqS *tmpl) : MqC(tmpl) {};

  private:
    // service to serve all incomming requests for token "HLWO"
    void MyFirstService () {
      SendSTART();
      SendC("Hello World");
      SendRETURN();
    }

    // define a service as link between the token "HLWO" and the callback "MyFirstService"
    void ServerSetup() {
      ServiceCreate("HLWO", CallbackF(&MyServer::MyFirstService));
    }
};

MqC的构造函数:
MqC::MqC (struct MqS *tmpl) {
  if (tmpl && (*(int*)tmpl) != MQ_MqS_SIGNATURE) {
    throw MqCSignatureException("MqS");
  } else {
    hdl = MqContextCreate(0, tmpl);
    MqConfigSetSelf (hdl, this);
    this->objInit();    <<<<<<<<<<<< This is the important part…
  }
}

现在objInit()应该可以检测到接口(interface)以正确配置对象了……
void MqC::objInit () {

    // use "hdl->setup.Parent.fCreate" to ckeck in context was initialized
    if (hdl->setup.Parent.fCreate != NULL) return;

    hdl->setup.Parent.fCreate = MqLinkDefault;
    hdl->setup.Child.fCreate = MqLinkDefault;

    // init the server interface
    IServerSetup * const iSetup = dynamic_cast<IServerSetup*const>(this);

    if (iSetup != NULL) {
      struct ProcCallS * ptr = (struct ProcCallS *) MqSysMalloc(MQ_ERROR_PANIC, sizeof(*ptr));
      ptr->type = ProcCallS::PC_IServerSetup;
      ptr->call.ServerSetup = iSetup;
      MqConfigSetServerSetup (hdl, ProcCall, static_cast<MQ_PTR>(ptr), ProcFree, ProcCopy);
    }
    ...

简而言之……行:
IServerSetup * const iSetup = dynamic_cast<IServerSetup*const>(this);

在构造函数中不起作用(总是返回NULL)……所以我需要稍后调用objInit()……这不好。

更新

如果我在顶级构造函数中使用objInit…可行...

→但是有可能避免这种情况(始终重复objInit())…并在MqC构造函数中获取顶级对象吗?
MyServer(MqS *tmpl) : MqC(tmpl) {
  objInit();
};

最佳答案

void MqC::objInit ()中,*thisMqCMqCIServerSetup没有任何关系,因此尝试将其强制转换为一个不起作用。

09-05 23:25