使用取消引用对象的虚函数调用 [英] Virtual function calling using dereference object
问题描述
我有一个基类指针指向一个派生类对象。我在下面的代码中使用两种不同的方式调用 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();
请注意
-
obj
在这里是错误的,因为它不是指向一个对象,而是一个指针, -
(* ptr).foo()
只是一个迂回的方式来执行ptr- ; foo()
。
obj
is a misnomer here, since it doesn't refer to an object, but to a pointer,(*ptr).foo()
is just a roundabout way to doptr->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屋!