为什么我们要使用两次引用运算符?

zur*_*fyx 1 c++ pointers reference class

我的问题是指带有类和关键字 this 的指针。

class class1 {
public:
    bool isitme(class1& temp){
        if(this == &temp)
            return true;
        else return false;
    }
};


int main () {
    class1 c3;
    class1* c2 = &c3;
    if(c3.isitme(*c2))
        cout << "c3 == c2"; //it is returning that
    system("pause");
}
Run Code Online (Sandbox Code Playgroud)

上面的代码是有效的,但我不明白的是为什么它只在bool isitme(class1& temp)if(this == &temp)位于同一函数中时才有效isitme()

我的意思是,我们已经在类参数中读取了 temp 的内存块class1& temp,并且应该能够将该内存块与关键字进行比较this。为什么只有当我双重获取引用 ( this == &temp) 时该函数才为 true?

谢谢

NPE*_*NPE 5

this是指针,而temp是引用。当您&temp在声明中写入时if,您正在获取 的地址temp。这会将其转换为一个指针,然后可以与 进行比较this