Ben*_*ett 7 c++ qt multiple-inheritance visual-studio qgraphicsitem
我创建了一个简单的程序,演示了我使用多重继承的Qt应用程序时遇到的运行时错误.继承树看起来像:
QGraphicsItem (abstract)
\
QGraphicsLineItem MyInterface (abstract)
\ /
\ /
MySubclass
Run Code Online (Sandbox Code Playgroud)
以下是代码:
/* main.cpp */
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsLineItem>
//simple interface with one pure virtual method
class MyInterface
{
public:
virtual void myVirtualMethod() = 0;
};
//Multiple inheritance subclass, simply overrides the interface method
class MySubclass: public QGraphicsLineItem, public MyInterface
{
public:
virtual void myVirtualMethod() { }
};
int main(int argc, char** argv)
{
QApplication app(argc, argv); //init QApplication
QGraphicsScene *scene = new QGraphicsScene(); //create scene
scene->addItem(new MySubclass()); // add my subclass to the scene
Q_FOREACH(QGraphicsItem *item, scene->items()) // should only have one item
{
MyInterface *mInterface = (MyInterface*)item; // cast as MyInterface
mInterface->myVirtualMethod(); // <-- this causes the error
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
调用我的接口方法时,Visual Studio中的调试会导致运行时错误:
Run-Time Check Failure #0 - The value of ESP was not properly
saved across a function call. This is usually a result of
calling a function declared with one calling convention with
a function pointer declared with a different calling convention.
Run Code Online (Sandbox Code Playgroud)
知道问题是什么吗?
因为你正在使用多重继承,所以vftable指向MyInterface*a的指针实际上是指向a的指针QGraphicsLineItem vftable.
A dynamic_cast会解决问题,因为它会返回正确的vftable
MyInterface* mInterface = dynamic_cast<MyInterface*>(item);
Run Code Online (Sandbox Code Playgroud)
一个简单的例子:
class A
{
public:
virtual void foo() = 0;
};
class B
{
public:
virtual void goo() {};
};
class C : public B, public A
{
public:
virtual void foo() {};
};
//....
B* c = new C; // c is at 0x00a97c78
A* a = (A*)c; // a is at 0x00a97c78 (vftable pointer of B)
A* a1 = dynamic_cast<A*>(c); // a1 is at 0x00a97c7c (vftable pointer of A)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12828 次 |
| 最近记录: |