繁体   English   中英

复制继承类的构造函数

[英]copy constructor of an inherited class

我试图定义一个类的副本构造函数,但我误会了。 我正在尝试使用此构造函数做一个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的副本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM