[英]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指针时会出错吗?
提前致谢。
问题不是关于addPoint
的Point*
参数,而是关于隐式this
指针参数:
operator=
被标记为const
函数,因此在其内部, this
是指向const
的指针。 因此,尝试对其调用非const
函数是行不通的。
您需要标记operator=
non- const
。
在相关说明中,您还从operator=
返回了一个指针 ,并通过非 const
引用获取了右侧操作数,这两者都是很奇怪的事情。
在重载运算符时, 强烈建议使用规范签名,例如,您可以在此处找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.