使用取消引用对象的虚函数调用 [英] Virtual function calling using dereference object

查看:127
本文介绍了使用取消引用对象的虚函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类指针指向一个派生类对象。我在下面的代码中使用两种不同的方式调用 foo()函数。为什么 Derived :: foo()在第一种情况下被调用?不应该(* obj).foo()调用 Base :: foo()取消引用?

I have a base class pointer pointing to a derived class object. I am calling foo() function by using two different ways in the code below. Why does Derived::foo() get called in the first case? Shouldn't (*obj).foo() call Base::foo() function as it has already been dereferenced?

    class Base
    {
    public:
        Base() {}
        virtual void foo() { std::cout << "Base::foo() called" << std::endl; }
        virtual ~Base() {};
    };

    class Derived: public Base
    {
    public:
        Derived() : Base() {}
        virtual void foo() {  std::cout << "Derived::foo() called" << std::endl; }
        virtual ~Derived() {};
    };

    int main() {
        Base* obj = new Derived();
   // SCENARIO 1
        (*obj).foo();
// SCENARIO 2
        Base obj1 = *obj;
        obj1.foo();

        return 0;
    }


推荐答案


// SCENARIO 1
(*obj).foo();


请注意


  1. obj 在这里是错误的,因为它不是指向一个对象,而是一个指针

  2. (* ptr).foo()只是一个迂回的方式来执行 ptr- ; foo()

  1. obj is a misnomer here, since it doesn't refer to an object, but to a pointer,
  2. (*ptr).foo() is just a roundabout way to do ptr->foo().

* ptr 不会导致对象, strong> 基本& 并且通过引用的虚拟函数调用经受动态分派,就像通过指针的调用一样。

*ptr doesn't result in an object, but in a reference Base& to the object. And a virtual function call through a reference is subject to dynamic dispatch, just as such a call through a pointer.


// SCENARIO 2
Base obj1 = *ptr;
obj1.foo();


你在这里做的是创建一个全新的对象通过< a href =http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c> 切片 :它只有基类部分 * ptr 。你想要的是这样:

What you do here is you create a totally new object through slicing: it just has the base class parts of *ptr. What you want instead is this:

Base& ref = *ptr;
ref.foo();

这篇关于使用取消引用对象的虚函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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