c++ - 为什么 C++ 中 "this"的地址会改变?

标签 c++ this memory-address

我有一个情况,我有一个 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/

相关文章:

c++ - 如何使用对未知大小数组的引用来调用函数?

c++ - 如何检查我们是否在 SQLite 中的事务中?

JavaScript 无法在 'getComputedStyle' : parameter 1 is not of type 'Window' 上执行 'Element'

java - 在构造对象时是否有在 java 中键入 this.x = x 的快捷方式?

swift - 快速打印可变内存地址

c++ - 将字符串转换为指针

c++ - 我如何杀死弹出窗口?

javascript - 将 "this"与 javascript 和 Jquery 一起使用

c - 如何通过C代码从绝对地址读取值

c++ - 从右到左的阅读顺序 : why isn't this calculated automatically?