继承类的复制构造函数

copy constructor of an inherited class

本文关键字:构造函数 复制 继承      更新时间:2023-10-16

我试图定义一个类的复制构造函数,但我弄错了。我正在尝试使用这个构造函数做QGraphicsRectItem的儿子:

QGraphicsRectItem( qreal x, qreal y, qreal width, qreal height, QGraphicsItem * parent = 0 )

这里有一些代码

QtL 定义的QGraphicsRectItem

QGraphicsRectItem( qreal x, qreal y, qreal width, qreal height, QGraphicsItem * parent = 0 )

Cell.h,儿子的班级:

Cell();
Cell(const Cell &c);
Cell(qreal x, qreal y, qreal width, qreal height, QGraphicsItem * parent = 0 );

Cell.cpp:

Cell::Cell() {}
/* got error defining this constructor (copy constructor) */
Cell::Cell(const Cell &c) :
    x(c.rect().x()), y(c.rect().y()),
    width(c.rect().width()), height(c.rect().height()), parent(c.parent) {}

Cell::Cell(qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent) : 
    QGraphicsRectItem(x, y, width, height, parent) {
    ...
    // some code
    ...
}

错误显示:

/../../../../cell.cpp:7: error: class 'Cell' does not have any field named 'x'
/../../../../cell.cpp:7: error: class 'Cell' does not have any field named 'y'
/../../../../cell.cpp:7: error: class 'Cell' does not have any field named 'width'
/../../../../cell.cpp:7: error: class 'Cell' does not have any field named 'height'
/../../../../cell.cpp:7: error: class 'Cell' does not have any field named 'parent'

感谢

您需要按照如下方式制作复制构造函数:

Cell::Cell(const Cell &c)
    :
        QGraphicsRectItem(c.rect().x(), c.rect().y(),
                          c.rect().width(), c.rect().height(),
                          c.parent())
{}

原因是您的Cell由于继承而QGraphicsRectItem。因此,构造函数的c参数也表示QGraphicsRectItem,因此您可以使用它的QGraphicsRectItem::rect()QGraphicsRectItem::parent()函数来构造新对象-c的副本。