【发布时间】:2013-01-22 13:37:50
【问题描述】:
我有某种对象工厂(基于模板),它非常适合我的目的。但现在我尝试使用派生自 QObject 和纯抽象类(接口)的类,但我遇到了奇怪的运行时错误。
这里是这个类的简单图(Derived)
class Interface {
public:
Interface(){}
virtual ~Interface(){}
virtual int getResult() = 0;
};
class Derived : public QObject, public Interface {
Q_OBJECT
public:
explicit Derived(QObject *parent = 0);
int getResult();
};
及其在derived.cpp中的实现:
#include "derived.h"
Derived::Derived(QObject *parent)
: QObject(parent) {
}
int Derived::getResult() {
return 55;
}
当我尝试将 void 指针强制转换为接口时,我会得到意外的(对我而言)行为,它可能是运行时错误,或其他方法调用(取决于类的大小)。
#include "derived.h"
void * create() {
return new Derived();
}
int main(int argc, char *argv[]) {
Interface * interface = reinterpret_cast<Interface *>(create());
int res = interface->getResult(); // Run-time error, or other method is called here
return 0;
}
你能解释一下为什么我不能将 void 指针转换为接口吗?有什么解决方法吗?
感谢您的回复
【问题讨论】:
-
reinterpret_cast?你试过dynamic_cast吗? -
我不能使用
dynamic_cast到void*,因为void*中没有RTTI。 (由于模板,我的工厂总是返回void*并将其转换为所需的模板类型,所以我必须使用void*- 这种方法有大量遗留代码。)
标签: c++ qobject reinterpret-cast