[英]When is a `static_cast<Base*>(static_cast<void*>(derived))` from a pointer to a derived class valid?
[英]Question of using static_cast on “this” pointer in a derived object to base class
这是一个取自Effective C ++ 3ed的例子 ,它说如果以这种方式使用static_cast
,则复制对象的基本部分,并从该部分调用该调用。 我想了解幕后发生的事情,有人会帮忙吗?
class Window { // base class
public:
virtual void onResize() { } // base onResize impl
};
class SpecialWindow: public Window { // derived class
public:
virtual void onResize() { // derived onResize impl;
static_cast<Window>(*this).onResize(); // cast *this to Window,
// then call its onResize;
// this doesn't work!
// do SpecialWindow-
} // specific stuff
};
这个:
static_cast<Window>(*this).onResize();
实际上与此相同:
{
Window w = *this;
w.onResize();
} // w.~Window() is called to destroy 'w'
第一行创建this
指向的SpecialWindow
对象的Window
基类子对象的副本。 第二行调用该副本上的onResize()
。
这一点很重要:你永远不会调用Window::onResize()
上的对象指向this
; 你叫Window::onResize()
上的副本, this
是你创建的。 复制后,不会触及this
指向的对象。
如果你想调用Window::onResize()
的对象指向this
, 你可以这样做这样的 :
Window::onResize();
为什么铸造? 如果你想调用Window的onResize(),就这样做,
Window::onResize(); //self-explanatory!
好吧,你也可以这样做,也使用static_cast,但你必须这样做,
static_cast<Window&>(*this).onResize();
//note '&' here ^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.