0

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

提前致谢

4

1 回答 1

1

您正在引用一个未初始化的指针ptr

如果我将主要更改为:

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

} 

有用

您也缺少虚拟 dtor

于 2012-08-12T15:43:35.043 回答