簡體   English   中英

為什么我不能設置 *this == class object

[英]Why can't I set *this == class object

我正在查看重載運算符 =。 為什么我可以設置 'this == &st' 但不能設置 '*this == st'?

StringBad & StringBad::operator=(const StringBad & st)
{
    if (this == &st)           // if the object assigned to itself, return to itself. 
        return *this;          // why compiler give error when I set *this ==st ?

/* blah blah
...
... */

    return *this;              // return reference to invoking object
}

比較 2 個指針與比較這些指針的值不同 例如

int *a, *b;
if(a == b) 
if (*a == *b) // not the same

當然,如果 2 個指針相同,那么它們指向相同的值,但反之則不然。

在這種情況下,檢查*this == st是否會編譯(假設operator==是為StringBad定義的),但這與檢查this == &st是否相同。

兩個不同的對象可以彼此相等,但這並不意味着它們是相同的。

考慮例如

#include <iostream>
#include <iomanip>

int main() 
{
    int x = 0;
    int y = 0;

    std::cout << "x == y is " << std::boolalpha << ( x == y ) << '\n';
    std::cout << "&x == &y is " << std::boolalpha << ( &x == &y ) << '\n';
}

程序 output 是

x == y is true
&x == &y is false

所以這個檢查this == &s是需要判斷這里是否有自賦值的。

為什么我可以設置this == &st但不能設置*this == st

我想你的意思是說,為什么我可以使用this == &st而不是*this == st

忽略這一點,答案是,是的,你可以,但這不一定是正確的做法。 它可能適合您的情況。 在這種情況下,您當然應該使用它。 當然,這意味着您需要首先為您的 class 實現operator==

這是一個示例,您不應使用*this == st使分配成為 noop。

假設您有一個 class 捕獲具有值和單位的物理量,假設您有:

object a ,表示 1 "m"。
object b ,表示 100“厘米”。

當您將ab進行比較時,您應該返回true 但是,當您將a分配給b或反之亦然時,IMO 您應該繼續分配。

暫無
暫無

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

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