[英]C++ dynamic_cast with multiple inheritance
Is possible to get object through dynamic_cast using multiple-inheritance ? 可以使用多重继承通过dynamic_cast获取对象吗? I prefer to skip compositional trick due to designing issue I have.
由于我的设计问题,我更喜欢跳过组合技巧。 Thanks,
谢谢,
#include <stdio.h>
namespace
{
template <typename T>
class Beta
{
protected:
Beta() { printf("Beta\n"); }
public:
virtual ~Beta() { printf("~Beta\n"); }
virtual void Run() = 0;
};
class Alpha
{
protected:
Alpha() { printf("Alpha\n"); }
public:
virtual ~Alpha() { printf("~Alpha\n"); }
virtual void Check() = 0;
template <typename T>
Beta<T>* GetBeta()
{
Beta<T>* b = dynamic_cast< Beta<T>* >(this);
if(b == NULL) printf("NULL !!\n");
return b;
}
};
template <typename T>
class Theta : public Alpha, Beta<T>
{
public:
void Run()
{
printf("Run !\n");
}
void Check()
{
printf("Check !\n");
}
};
}
int main(int argc, const char* argv[])
{
Alpha* alpha = new Theta<int>();
Beta<int>* beta = alpha->GetBeta<int>();
alpha->Check();
if(beta) beta->Run();
delete alpha;
return 0;
}
The result from above code is 上面代码的结果是
Alpha Beta NULL !! Alpha Beta NULL !! Check !
检查! ~Beta ~Alpha
~Beta~Alpha
Well, if I replace: 好吧,如果我更换:
public Alpha, Beta<T>
with: 有:
public Alpha, public Beta<T>
Things will work. 事情会奏效。 There is always a devil in the details...
细节总是有魔鬼......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.