[英]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.