我有以下情况。有两个基类: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 类对象?
提前致谢