C++对象相等

use*_*378 8 c++ pointers equality

我有一个类MyCloth和一个该类的对象实例,我实例化如下:

MyCloth** cloth1;
Run Code Online (Sandbox Code Playgroud)

在程序的某一点上,我会做这样的事情:

MyCloth** cloth2 = cloth1;
Run Code Online (Sandbox Code Playgroud)

然后在某个时候以后,我要检查,看是否cloth1cloth2是相同的.(像Java中的对象相等,只有这里,MyCloth是一个非常复杂的类,我不能构建一个isEqual函数.)

我怎样才能进行这种平等检查?我想也许可以检查他们是否指向相同的地址.这是一个好主意吗?如果是这样,我该怎么做?

And*_*mas 14

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

MyCloth* pcloth1 = ...
MyCloth* pcloth2 = ...
if ( pcloth1 == pcloth2 ) {
    // Then both point at the same object.
}   
Run Code Online (Sandbox Code Playgroud)

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

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

bool operator== ( MyCloth & lhs, MyCloth & rhs )
{
   return ...
}
Run Code Online (Sandbox Code Playgroud)

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

MyCloth cloth1 = ...
MyCloth cloth2 = ...
if ( cloth1 == cloth2 ) {
    // Then the two objects are considered to have equal values.
}   
Run Code Online (Sandbox Code Playgroud)


Chr*_*sCM 5

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

someClass instance1;
someClass instance2;
Run Code Online (Sandbox Code Playgroud)

您可以通过重载此类的 < 运算符来实现此目的。

class someClass
{
    
    bool operator<(someClass& other) const
    {
        //implement your ordering logic here
    }
};
Run Code Online (Sandbox Code Playgroud)

如果您想要做的是比较,并查看这些对象是否实际上是同一个对象,则可以进行简单的指针比较以查看它们是否指向同一个对象。我认为你的问题措辞不好,我不确定你要问哪个。

编辑:

对于第二种方法,确实非常简单。您需要访问对象的内存位置。您可以通过多种不同的方式访问它。以下是一些:

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

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

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


instancePointer == instanceVariable;
Run Code Online (Sandbox Code Playgroud)

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

instancePointer == &instanceVariable; 
Run Code Online (Sandbox Code Playgroud)

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

instancePointer == instanceVaribalePointer;  
Run Code Online (Sandbox Code Playgroud)

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

instanceVariablePointer == &instanceVariable;
Run Code Online (Sandbox Code Playgroud)

这也是有效的并且会导致 TRUE。

instanceVariable == *instanceVariablePointer;
Run Code Online (Sandbox Code Playgroud)

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