c ++将指针传递给方法

时间:2015-11-04 11:19:08

标签: c++ pointers

我有以下功能:

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);
}

我相信每个人都明白对象意味着什么,他们非常直截了当。 第一个方法位于Triangle类中,它继承自Polygon。

当我使用

时问题出现在第一种方法中
this->addPoint(other.getPoint(i));

Eclipse声明其无效参数。 当getPoint返回Point指针并且AddPoint函数需要Point指针时,我能解释为什么它会出错?

提前致谢。

1 个答案:

答案 0 :(得分:3)

问题不在于Point*的{​​{1}}参数,而在于隐式addPoint指针参数:

this被标记为operator=函数,因此在其中const是指向this的指针。因此,尝试在其上调用非const函数不起作用。

您需要标记const非 - operator=

在相关说明中,您还要从const返回指针,并通过 - operator=获取右侧操作数参考,这两个都是奇怪的事情。

当重载运算符时,建议强烈使用规范签名,您可以找到它们,例如here