韩冰 发表于 2005-1-26 01:18

求得类成员地址的又一个方法

<P>  </P>
<P>可以求得成员函数,成员变量的地址 </P>
<P>也可以得到普通变量和函数的地址或者值 </P>
<P>换句话,就是又一个版本的AnythingToLong </P>
<P>优化过后,毫无性能损失 </P>
<P>所以我觉得是一个较好的解决办法 </P>
<P>  </P>
<P>// test.cpp : Defines the entry point for the console application. </P>
<P>// </P>
<P>  </P>
<P>#include "stdafx.h" </P>
<P>  </P>
<P>template&lt;class T&gt; </P>
<P>inline unsigned long ValueOf(const T &amp;value) </P>
<P>{ </P>
<P>        return *(unsigned long*)(&amp;value); </P>
<P>} </P>
<P>  </P>
<P>template&lt;class T&gt; </P>
<P>inline int SizeOfArray(const T &amp;array) </P>
<P>{ </P>
<P>        return sizeof(array)/sizeof(array); </P>
<P>} </P>
<P>  </P>
<P>class Test </P>
<P>{ </P>
<P>public: </P>
<P>        int a,b; </P>
<P>        void f(){} </P>
<P>}; </P>
<P>  </P>
<P>int main(int argc, char* argv[]) </P>
<P>{ </P>
<P>        int t; </P>
<P>        int n=1000; </P>
<P>  </P>
<P>        //      cout&lt;&lt;SizeOfArray(t)&lt;&lt;endl; </P>
<P>        cout&lt;&lt;ValueOf(&amp;Test::a)&lt;&lt;endl; </P>
<P>        cout&lt;&lt;ValueOf(&amp;Test::b)&lt;&lt;endl; </P>
<P>        cout&lt;&lt;ValueOf(&amp;Test::f)&lt;&lt;endl; </P>
<P>  </P>
<P>        cout&lt;&lt;ValueOf(&amp;t)&lt;&lt;endl; </P>
<P>        cout&lt;&lt;(long)&amp;t&lt;&lt;endl; </P>
<P>  </P>
<P>        cout&lt;&lt;ValueOf(n)&lt;&lt;endl; </P>
<P>  </P>
<P>        return 0; </P>
<P>} </P>
<P>  </P>
<P>//运行结果 </P>
<P>  </P>
<P>16 </P>
<P>0 </P>
<P>4 </P>

<P>4198425 </P>
<P>6684088 </P>
<P>6684088 </P>
<P>1000 </P>
<P>Press any key to continue </P>
页: [1]
查看完整版本: 求得类成员地址的又一个方法