0

此错误出现在第 4 行:

void QPiece::setPosition( QPoint value )
{
    _position = value;
    QWidget* parentWidget = static_cast<QWidget *>( _board->Cells[value.x() ][ value.y() ]);
if (parentWidget->layout()) {
    parentWidget->layout()->addWidget( this ); }
else { 
     QHBoxLayout *layout = new QHBoxLayout( parentWidget );
     layout->setMargin(0); 
     layout->addWidget(this); 
     parentWidget->setLayout(layout);
}
    this->setParent( _board->Cells[ value.x() ][ value.y() ] );
}

下面是函数 Cells() 的定义:

class QBoard : public QWidget
{
     Q_OBJECT
     public:
          QCell *Cells[8][8];
          QBoard(QWidget *parent = 0);
          void drawCells();

     private:
          void positionCells();
};

我想我做错了什么,但是什么?提前致谢。 这是 QCell 的类型,我认为 QWidget 是 QLabel 的父级

class QCell:public QLabel

{
     Q_OBJECT

public:
     QCell( QPoint position, QWidget *parent = 0 );

private:
     QGame *_game;
     QPoint _position;
protected:
      void mousePressEvent( QMouseEvent *ev );
 };
4

1 回答 1

5

This should work without a cast at all, the conversion from derived to base is implicit.

A likely cause of this error would be that you only have a forward declaration of QCell visible in that compilation unit, which would trigger this error. You need to have the complete class declaration visible for the compiler to know whether that conversion is legal or not.

Example:

#include <QWidget>

class QCell;

int main(int argc, char **argv)
{
    QCell *w = 0;
    QWidget *q = static_cast<QWidget*>(w);
}
main.cpp: In function ‘int main(int, char**)’:
main.cpp:8:41: error: invalid static_cast from type ‘QCell*’ to type ‘QWidget*’
于 2013-06-08T10:30:33.213 回答