我们怎么能在那个类中使用运算符呢
How can we use an operator in that class?
我想在类中编写一个函数,使用我稍后在该类中定义的运算符。但我不知道如何向运算符显示,现在必须使用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
。
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;
}
};
相关文章:
- 取消引用运算符不能重载
- Arduino millis() - millis() 怎么能等于 0 以外的任何东西?
- 为什么文本运算符不能正常模板化?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 运算符'<'不能应用于类型 'string' 和 'string' 的操作数
- 我们怎么能 me 字符数组只接受 C++ 中的字母
- C++自定义删除运算符不能正常工作?
- 你怎么能emplace_back错误的类型?
- 我怎么能有一个以2D数组为参数的函数,而数组有一个我想更改的参数/维度
- 我怎么能把它转换成c++呢
- 我有一个调用ID3D11DeviceContext::CopySubresourceRegion的循环.我怎么能强制等待
- 类定义怎么能不占用内存?
- 怎么能用memcpy复制工会简单的成员?
- 为什么 test2 + test3 的运算符<<不能过载?
- 当 do-while 再次启动时,对象将被删除.我怎么能阻止它
- 二元运算符"<<"不能应用于类型 "wostream" 和 "string" 的表达式
- 指针怎么能有一个字符串作为它的值
- 一个函数怎么能完成它的目标,只是在返回主函数后崩溃?
- 这两个指针怎么能有相同的值
- 我们怎么能在那个类中使用运算符呢