【问题标题】:How can we use an operator in that class?我们如何在该类中使用运算符?
【发布时间】:2012-01-27 21:26:41
【问题描述】:

我想在类中编写一个函数,使用我稍后在该类中定义的运算符。但我不知道如何向运算符显示现在您必须使用 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))
       //...
}

【问题讨论】:

  • bool operator==(Point p) const
  • 同样向量应该通过const vector&lt;Point&gt;&amp;传递,searchArea也应该是一个const函数,并且应该返回truefalse
  • 更好:bool operator==(const Point &amp;p) const

标签: c++ class operator-keyword


【解决方案1】:

你有/* what ?? */你想要*this

【讨论】:

  • 谢谢!但为什么要指向这个?我的意思是为什么 *this 而不是 this?
  • 这不是指向this 的指针,而是取消引用this 指针以访问this 指向的对象。
【解决方案2】:

我见过两种方法:

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

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

【讨论】:

    【解决方案3】:

    this 在 C++ 中是指向当前对象的指针。如果要访问实际对象,则需要添加取消引用运算符*(与 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;
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多