gpt4 book ai didi

c++ - 这背后的地址是否保证与对象的变量相同

转载 作者:行者123 更新时间:2023-12-01 14:03:46 25 4
gpt4 key购买 nike

在以下代码的情况下:

#include<iostream>

class Sample
{
public:
Sample* getSelf()
{
return this;
}
};

int main()
{
Sample s;

if(reinterpret_cast<void*>(&s) == reinterpret_cast<void*>(s.getSelf()))
std::cout << "Same address" << std::endl;

return 0;
}

if 语句中的条件是否保证为真?

我已将类型转换发送至 void*确保比较原始地址,以防在比较特定指针类型时出现一些怪癖。

最佳答案

是你的 if声明保证为 true . thisgetSelf()是指向实例的指针。

&smain也是指向该实例的指针。

正如您怀疑的那样,类型转换是不必要的。

关于c++ - 这背后的地址是否保证与对象的变量相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60953079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com