簡體   English   中英

c ++將指針傳遞給方法

[英]c++ passing pointers to method

我具有以下功能:

Triangle* operator=(Triangle& other) const
{
    for (unsigned int i = 0; i < other.getNumOfPoints(); i++)
    {
        this->addPoint(other.getPoint(i));
    }

    color = other.color;

    //type stays the same
    return this;
}


Point* Polygon::getPoint(int index) const
{
    return _points.at(index);
}

void Polygon::addPoint(Point* p) {
    Point* newp = new Point; //create a copy of the original pt
    newp->setX(p->getX());
    newp->setY(p->getY());
    _points.push_back(newp);
}

我確信每個人都明白對象的含義,它們很簡單。 第一個方法位於從Polygon繼承的Triangle類中。

問題是我使用時的第一種方法

this->addPoint(other.getPoint(i));

Eclipse聲明其Invalid參數。 我可以解釋為什么當getPoint返回Point指針而AddPoint函數需要Point指針時會出錯嗎?

提前致謝。

問題不是關於addPointPoint*參數,而是關於隱式this指針參數:

operator=被標記為const函數,因此在其內部, this是指向const的指針。 因此,嘗試對其調用非const函數是行不通的。

您需要標記operator= non- const


在相關說明中,您還從operator=返回了一個指針 ,並通過 const引用獲取了右側操作數,這兩者都是很奇怪的事情。

在重載運算符時, 強烈建議使用規范簽名,例如,您可以在此處找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM