C ++对象等同 [英] C++ object equality
问题描述
我有一个类 MyCloth
和该类的一个对象实例,像我这样实例化:
I have a class MyCloth
and one one object instance of that class that I instantiated like this:
MyCloth** cloth1;
在程序中的某一点,我会做这样的事情:
And at one point in the program, I will do something like this:
MyCloth** cloth2 = cloth1;
然后在某个时候,我想检查 cloth1
和 cloth2
是相同的。 (类似Java中的对象平等,只有在这里, MyCloth
是一个非常复杂的类,我不能构建 isEqual
function。)
And then at some point later, I want to check to see if cloth1
and cloth2
are the same. (Something like object equality in Java, only here, MyCloth
is a very complex class and I can''t build an isEqual
function.)
我如何做这个相等检查?我想可能检查他们是否指向相同的地址。这是个好主意吗?
How can I do this equality check? I was thinking maybe checking if they point to the same addresses. Is that a good idea? If so, how do I do that?
推荐答案
您可以通过比较地址由两个指针保持。你提到Java;这与类似于两个引用相等的测试。
You can test for object identity by comparing the addresses held by two pointers. You mention Java; this is similar to testing that two references are equal.
MyCloth* pcloth1 = ...
MyCloth* pcloth2 = ...
if ( pcloth1 == pcloth2 ) {
// Then both point at the same object.
}
您可以通过比较对象两个对象的内容。在C ++中,这通常通过定义 operator ==
来完成。
You can test for object equality by comparing the contents of two objects. In C++, this is usually done by defining operator==
.
class MyCloth {
friend bool operator== (MyCloth & lhs, MyCloth & rhs );
...
};
bool operator== ( MyCloth & lhs, MyCloth & rhs )
{
return ...
}
使用operator ==定义,可以比较等式:
With operator== defined, you can compare equality:
MyCloth cloth1 = ...
MyCloth cloth2 = ...
if ( cloth1 == cloth2 ) {
// Then the two objects are considered to have equal values.
}
这篇关于C ++对象等同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!