求教类型强制转换的规律 (困惑于MFC中的METHOD_PROLOGUE宏)
小弟最近在学习COM. 在模拟其原理的过程中碰到下面的问题, 源代码见下.
wrap指针是 : 0xe380f54
wrap.m_first地址是 : 0xe380f58
offsetof(wrap, m_first)的值是 : 4
show1中运行 this 得值是 : 0xe380f58, 也就是与wrap.m_first的
值是一样的.
我原本设想, 在show1中运行 this - offsetof(wrap, m_first) 后就应该是
0xe380f54, 也就是可以得出 wrap 指针的值. 可事实上, 得出来的是 0xe380f4c.
非要按(wrap*)((char*)this-offsetof(wrap, m_first)) 才能够得到正确的结果
0xe380f54. 即使用 (wrap*)(this - offsetof(wrap,m_first)) 得出的也是错误 !
这一段运算的原型来自于MFC中的 METHOD_PROLOGUE 宏.
十分困惑使用类型强制的时机. 在MFC中使用类型强制很普遍, 有什么规律可以遵守?
十分感谢 !!!
# include "iostream.h"
# include "stddef.h"
struct first {
virtual void set1()=0;
virtual void show1()=0;
};
class wrap {
private :
int a, b;
public :
wrap() { cout << "\n constructor"; };
~wrap() { cout << "\n destructor"; };
class xfirst : public first {
public :
void set1() { };
void show1();
} m_first;
};
void wrap::xfirst::show1() { cout << "\n" << this << " " << (wrap*)((char*)this-offsetof(wrap,m_first)); };
void main()
{
wrap* x=new(wrap);
cout << "\n" << x;
x->m_first.show1();
delete x;
}