2012-04-03 11 views
1

Könnte mir bitte jemand sagen, warum die Dynamic_cast im folgenden Code (fünf Zeilen von unten) fehlschlägt? Ich fürchte, es ist etwas offensichtlich, aber ich kann es nicht sehen. Downcasting in Qt

//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; 
} 

Antwort

3
Child(QObject * parent = 0) {} 

Sie tun nichts mit dem parent Zeiger - Sie werfen es einfach weg. Sie sollten den Zeiger auf QObject Konstruktor wie folgt passieren:

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

Ohne, dass der Standardkonstruktor von QObject wird und das übergeordnete Argument ignoriert aufgerufen werden.

+0

Noch offensichtlicher als ich befürchtet hatte (können Sie mir sagen, dass ich neu bin?) Danke! – planarian