簡體   English   中英

C ++對象相等

[英]C++ object equality

我有一個類MyCloth和我實例化的那個類的一個對象實例:

MyCloth** cloth1;

在程序的某一點上,我會做這樣的事情:

MyCloth** cloth2 = cloth1;

然后在某個時候,我想檢查一下cloth1cloth2是否相同。 (像Java中的對象相等,只有在這里, MyCloth是一個非常復雜的類,我不能構建一個isEqual函數。)

我怎樣才能進行這種平等檢查? 我想也許可以檢查他們是否指向相同的地址。 這是一個好主意嗎? 如果是這樣,我該怎么做?

您可以通過比較兩個指針所持有的地址來測試對象標識 你提到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.
}   

如果您想定義一種方法,可以通過該方法對客戶類的一組對象進行比較。 例如:

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的結果;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM