在这个“this”上使用static_cast的问题。指针在派生对象中的基类 [英] Question of using static_cast on "this" pointer in a derived object to base class

查看:612
本文介绍了在这个“this”上使用static_cast的问题。指针在派生对象中的基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个取自 Effective C ++ 3ed 的例子,它说如果 static_cast 这样使用,对象的基础部分被复制,并从该部分调用调用。我想知道发生了什么,会有人帮助吗?

this is an example taken from Effective C++ 3ed, it says that if the static_cast is used this way, the base part of the object is copied, and the call is invoked from that part. I wanted to understand what is happening under the hood, will anyone help?

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
};


推荐答案

This:

static_cast<Window>(*this).onResize();

实际上与此相同:

{
    Window w = *this;
    w.onResize();
}   // w.~Window() is called to destroy 'w'

第一行创建指向的 SpecialWindow 对象的 Window 基类子对象的副本这。第二行在该副本上调用 onResize()

The first line creates a copy of the Window base class subobject of the SpecialWindow object pointed to by this. The second line calls onResize() on that copy.

这很重要:你从不调用 C> Window :: onResize()这个您在创建的的副本上调用 Window :: onResize()

This is important: you never call Window::onResize() on the object pointed to by this; you call Window::onResize() on the copy of this that you created. The object pointed to by this is not touched after you make the copy it.

如果要调用

If you want to call Window::onResize() on the object pointed to by this, you can do so like this:

Window::onResize();

这篇关于在这个“this”上使用static_cast的问题。指针在派生对象中的基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆