使用dynamic_cast指向其他派生类对象

时间:2012-08-12 15:18:47

标签: c++ oop dynamic-cast

我有以下情况。有两个基类:Base1,Base2和两个派生类:Derived,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中调用“Derived”类的这个函数,但是dynamic_cast失败了。 我无法在sysCommandExecutor类中创建该函数,因为这是其他人的代码。 如何使sysCommandExecutor类中的ptr指针指向Derived类对象??

提前致谢

1 个答案:

答案 0 :(得分:1)

您正在引用未初始化的指针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