我有以下情况。有两个基类:Base1,Base2和两个派生类:派生sysCommandExecutor,它们派生如下:

#include <iostream>
using namespace std;

class Base1 { virtual void dummy() {} };
class Base2 { virtual void dumy() {} };
class Derived: virtual public Base1, public Base2
{ int a; };

class sysCommandExecutor : public Base2
{
public:
int b;
Base1 *ptr;
void func(void);
};

void sysCommandExecutor::func(void)
{
  Derived *d;
  d = dynamic_cast<Derived *>(ptr);
  if (d == NULL)
  std::cout << "This is NULL" << std::endl;
  else
  {
  // Call a function of Derived class
  }
}

int main () {
   try {
   sysCommandExecutor * sys =  new sysCommandExecutor;
   sys->func();
   return 0;
   }
}


我想在func中调用“派生”类的此函数,但dynamic_cast失败。
我无法在sysCommandExecutor类中创建该函数,因为那是其他人的代码。
如何使sysCommandExecutor类中的ptr指针指向Derived类对象?

提前致谢

最佳答案

您引用的是未初始化的指针ptr

如果我将main更改为:

int main () {
   sysCommandExecutor * sys =  new sysCommandExecutor;
   sys->ptr=new Derived;
   sys->func();
   delete dynamic_cast<Derived *>(sys->ptr);
   delete sys;
   return 0;

}


有用

您也缺少虚拟dtor

08-27 10:08