簡體   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