C++@子类类型转换为父类类型 static_cast(*this) to a base class create a temporary copy.
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 ... };
Effective C++: What you might not expect is that it does not invoke that function on the current object! Instead, the cast creates a new, temporary copy of the base class part of *this, then invokes onResize on the copy!
*******************************************************************************************
Contrast:
static_cast<Window>(*this)
with:
static_cast<Window&>(*this)
One calls the copy constructor, the other does not.
*******************************************************************************************
Because you are casting actual object not a pointer or reference. It's just the same with casting double
to int
creates new int
- not reusing the part of double
.
double类型转换为int型会创建一个新的int型变量?
*******************************************************************************************
上面的句子static_cast<Window>(*this).onResize();千万别改成下面这样,那样会更悲惨!
}