在Qt

时间:2012-04-03 18:27:46

标签: qt casting dynamic-cast

有人可以告诉我为什么以下代码中的dynamic_cast(从底部五行)失败了吗?我担心这是明显的,但我看不到它。

//dynamic_cast.h
#ifndef DYNAMIC_CAST_H
#define DYNAMIC_CAST_H
#include <QObject>
class Parent: public QObject
{
 Q_OBJECT
 public:
 Parent(QObject * parent = 0) {}
};
class Child: public QObject
{
 Q_OBJECT
 public:
 Child(QObject * parent = 0) {}
};
#endif // DYNAMIC_CAST_H


//dynamic_cast.cpp
#include <iostream>
#include "dynamic_cast.h"
using namespace std;
int main (int argc, char *argv[])
{
  Parent * aParent = new Parent;
  Child * aChild = new Child(aParent);
  Parent * anotherParent = dynamic_cast <Parent *>(aChild->parent());
  if (anotherParent==0)
      cout << "Assigned null pointer" << endl;
  else cout <<"No problem!";
  return 0;
}

1 个答案:

答案 0 :(得分:3)

Child(QObject * parent = 0) {}

你没有用parent指针做任何事情 - 你只是把它扔掉了。您应该将指针传递给QObject的构造函数,如下所示:

Child(QObject * parent = 0) : QObject(parent)
{}

如果没有它,将调用QObject的默认构造函数并忽略父参数。