我们可以通过将reinterpret_cast将类对象强制转换成内置类型的引用,然后对其进行取地址操作如下

 

代码
#include <iostream>
using namespace std;

struct A
{
int * p;
int *operator&(){return p;}
};


template
<class T>
T
* addressof(T & val)
{
return reinterpret_cast<T*>(&reinterpret_cast<int&>(val));
}

template
<class T>
T
const * addressof(T const & val)
{
return reinterpret_cast<T const*>(&reinterpret_cast<int const&>(val));
}


int main()
{
A a;
a.p
= NULL;
A
* pA = NULL;
pA
=addressof(a);
cout
<<pA<<endl;

A
const ca;
A
const*pca;
pca
= addressof(ca);
return 0;
}

 

相关文章:

  • 2021-06-20
  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
  • 2021-11-27
  • 2022-12-23
  • 2021-07-10
猜你喜欢
  • 2022-12-23
  • 2021-05-16
  • 2022-12-23
  • 2021-08-28
  • 2021-05-11
  • 2022-12-23
  • 2021-08-27
相关资源
相似解决方案