简体   繁体   English

为什么这个方法不像我期望的那样调用虚拟?

[英]Why isn't this method call virtual like I was expecting?

I want to ask what happen, when I use virtual functions without pointers ? 我想问一下,当我使用没有指针的虚函数时会发生什么? for example: 例如:

#include <iostream>
using namespace std;
class Parent
{
 public:
   Parent(int i) { }
   virtual void f() { cout<<"Parent"<<endl; }
};

class Child : public Parent
{
 public:
   Child(int i) : Parent(i) { }
   virtual void f() { Parent::f(); cout<<" Child"<<endl; }
};

int main()
{
    Parent a(2);
    Parent b = Child(2);
    a.f();
    b.f();
    return 0;
}

^^ Why doesn't it work ? ^^为什么不起作用? Where can I find something about how virtual methods really work? 我在哪里可以找到有关虚拟方法如何工作的内容?

This effect is called "slicing." 这种效果称为“切片”。

Parent b = Child(2); // initializes a new Parent object using part of Child obj

In C++, the dynamic type may only differ from the static type for references or pointers. 在C ++中,动态类型可能只与引用或指针的静态类型不同。 You have a direct object. 你有一个直接的对象。 So, your suspicion was essentially correct. 所以,你的怀疑基本上是正确的。

Try the following: 请尝试以下方法:

std::auto_ptr<Parent> b = new Child(2);

In your code you copy part of Child object to b . 在您的代码中,您将Child对象的一部分复制到b This is so called object slicing . 这就是所谓的对象切片

Virtual function mechanism is enabled only if the virtual function is called through either an appropriate reference or an appropriate pointer. 仅当通过适当的引用或适当的指针调用虚函数时,才启用虚函数机制。 Note that virtual function call mechanism is suppressed in constructor/destructor or while using the :: operator. 请注意,虚构函数调用机制在构造函数/析构函数中或使用::运算符时被抑制。

If the code is as shown below, virtual function mechanism will be enabled. 如果代码如下所示,将启用虚拟功能机制。

Child c;
Parent &a = c;
a.f();

Without pointers, the call is statically bound, even if it is a virtual function call. 没有指针,即使是虚函数调用,调用也是静态绑定的。

EDIT 2: 编辑2:

$10.3/6 - [Note: the interpretation of the call of a virtual function depends on the type of the object for which it is called (the dynamic type), whereas the interpretation of a call of a nonvirtual member function depends only on the type of the pointer or reference denoting that object (the static type) (5.2.2). $ 10.3 / 6 - [注意:虚函数调用的解释取决于调用它的对象的类型(动态类型),而非虚拟成员函数调用的解释仅取决于类型表示该对象的指针或引用(静态类型)(5.2.2)。 ] ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM