简体   繁体   English

c ++将指针传递给方法

[英]c++ passing pointers to method

I have the following functions: 我具有以下功能:

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

I am sure each understand what the objects mean, they are pretty straight forward. 我确信每个人都明白对象的含义,它们很简单。 First method is located inside Triangle class which inherit from Polygon. 第一个方法位于从Polygon继承的Triangle类中。

Problem is in the first method when I use 问题是我使用时的第一种方法

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

Eclipse states its Invalid argument. Eclipse声明其Invalid参数。 Can I get an explanation of why is it error when getPoint returns Point pointer and AddPoint function requires a Point pointer? 我可以解释为什么当getPoint返回Point指针而AddPoint函数需要Point指针时会出错吗?

Thanks in advance. 提前致谢。

The problem is not about the Point* argument of addPoint , but about the implicit this pointer argument: 问题不是关于addPointPoint*参数,而是关于隐式this指针参数:

operator= is marked as a const function, so inside it, this is a pointer-to- const . operator=被标记为const函数,因此在其内部, this是指向const的指针。 Thus trying to call a non- const function on it doesn't work. 因此,尝试对其调用非const函数是行不通的。

You need to mark operator= non- const . 您需要标记operator= non- const


On a related note, you're also returning a pointer from operator= and taking the right-hand operand by non - const reference, both of which are weird things to do. 在相关说明中,您还从operator=返回了一个指针 ,并通过 const引用获取了右侧操作数,这两者都是很奇怪的事情。

When overloading operators, it's strongly recommended to use the canonical signatures, which you can find eg here . 在重载运算符时, 强烈建议使用规范签名,例如,您可以在此处找到。

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

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