我们怎么能在那个类中使用运算符呢

How can we use an operator in that class?

本文关键字:运算符 怎么能 我们      更新时间:2023-10-16

我想在类中编写一个函数,使用我稍后在该类中定义的运算符。但我不知道如何向运算符显示,现在必须使用YOUR(x,y)的值。(我看到有人在php中使用$this->func_name。但这里我不知道。

class Point
{
  public:
    int x;
    int y;
    bool operator==(Point p)
    {
        if (x == p.x && y == p.y)
            return 1;
        return 0;
    }
    bool searchArea(vector <Point> v)
    {
        for (int i = 0; i < v.size(); i++)
            if (v[i] == /* what ?? */  )
                return 1;
        return 0;
    }
};
int main()
{
    //...
.
.
. 
    if (p.searchArea(v))
       //...
}

如果有/* what ?? */,则需要*this

我看到了两种方法:

 if ( *this == v[i] )
 if ( operator==(v[i]) )

this是指向当前对象的指针。*this是对当前对象的引用。由于比较运算符采用引用,因此必须取消对this指针的引用。或者,您可以直接调用成员函数,该函数隐式传递this

C++中的this是指向当前对象的指针。如果您想访问实际的对象,您需要添加取消引用运算符*(不同于Java)。例如:(*this).x
class Point
{
  public:
    int x;
    int y;

    bool operator==(Point p)
    {
        if (x == p.x && y == p.y)
            return 1;
        return 0;
    }
    bool searchArea(vector <Point> v)
    {
        for (int i = 0; i < v.size(); i++)
            if (v[i] == *this  )
                return 1;
        return 0;
    }
};