11

我有一个类MyCloth和该类的一个对象实例,我像这样实例化:

MyCloth** cloth1;

在程序的某一时刻,我会做这样的事情:

MyCloth** cloth2 = cloth1;

cloth1然后在稍后的某个时候,我想检查一下是否cloth2相同。(像 Java 中的对象相等,仅在这里,MyCloth是一个非常复杂的类,我无法构建isEqual函数。)

我怎样才能做这个平等检查?我在想也许检查它们是否指向相同的地址。这是一个好主意吗?如果是这样,我该怎么做?

4

2 回答 2

21

您可以通过比较两个指针持有的地址来测试对象身份。你提到Java;这类似于测试两个引用是否相等。

MyCloth* pcloth1 = ...
MyCloth* pcloth2 = ...
if ( pcloth1 == pcloth2 ) {
    // Then both point at the same object.
}   

您可以通过比较两个对象的内容来测试对象是否相等。在 C++ 中,这通常通过定义operator==.

class MyCloth {
   friend bool operator== (MyCloth & lhs, MyCloth & rhs );
   ...
};

bool operator== ( MyCloth & lhs, MyCloth & rhs )
{
   return ...
}

定义 operator== 后,您可以比较相等性:

MyCloth cloth1 = ...
MyCloth cloth2 = ...
if ( cloth1 == cloth2 ) {
    // Then the two objects are considered to have equal values.
}   
于 2013-05-30T19:05:07.883 回答
4

如果您想定义一种方法来对您的客户类的一组对象进行比较。例如:

someClass instance1;
someClass instance2;

您可以通过为此类重载 < 运算符来做到这一点。

class someClass
{

    bool operator<(someClass& other) const
    {
        //implement your ordering logic here
    }
};

如果你想做的是比较,看看对象是否是同一个对象,你可以做一个简单的指针比较,看看它们是否指向同一个对象。我认为您的问题措辞不佳,我不确定您要问哪个。

编辑:

对于第二种方法,它真的很容易。您需要访问对象的内存位置。您可以通过许多不同的方式访问它。这里有几个:

class someClass
{

    bool operator==(someClass& other) const
    {
        if(this == &other) return true; //This is the pointer for 
        else return false;
    }
};

注意:我不喜欢上述内容,因为 == 运算符通常比仅比较指针更深入。对象可以表示具有相似品质但并不相同的对象,但这是一种选择。你也可以这样做。

someClass *instancePointer = new someClass();
someClass instanceVariable;
someClass *instanceVariablePointer = &instanceVariable;


instancePointer == instanceVariable;

这是无意义的和无效/错误的。如果它甚至可以编译,取决于您的标志,希望您使用的标志不允许这样做!

instancePointer == &instanceVariable; 

这是有效的,并且会导致错误。

instancePointer == instanceVaribalePointer;  

这也是有效的,并且会导致错误。

instanceVariablePointer == &instanceVariable;

这也是有效的,将导致 TRUE

instanceVariable == *instanceVariablePointer;

这将使用我们上面定义的 == 运算符来获得 TRUE 的结果;

于 2013-05-30T18:31:52.547 回答