我有一个情况,我有一个 Foo 类型的对象,在这个对象中调用它自己的方法不知何故失去了它自己在“this”中的地址。我已经定义了这些函数:
// Bar has an instance of foo, and wishes to call a function001()...
Bar::doThingWithFoo(){
// foo is at address 0x1a7bbb70 here...
foo->function001();
}
// The definition of function001(). The address of "this" is as expected.
Foo::function001(){
// the address of "this" is 0x1a7bbb70 here...
this->function002();
}
Foo::function002(){
// but the address of "this" is 0xbfffe090 here!!!
// bad things happen, as you might expect.
this->getMyProperty()->doThing();
}
为什么会发生这样的事情?
最佳答案
也许你正在使用多重继承,这导致 this
的指针值依赖于上下文:
http://frogchunk.com/documentation/lang/cpp/Multiple_inheritance_and_the_this_pointer.pdf
如果您使用 C 转换而不是 dynamic_cast
,则会导致问题。
关于c++ - 为什么 C++ 中 "this"的地址会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285280/