c++ - 为什么这个方法调用不像我预期的那样是虚拟的?

标签 c++ object-slicing

我想问一下,当我使用没有指针的虚函数时会发生什么?例如:

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

^^ 为什么它不起作用? 我在哪里可以找到有关虚拟方法实际工作原理的信息?

最佳答案

这种效果称为“切片”。

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

在 C++ 中,动态类型可能仅与引用或指针的静态类型不同。你有一个直接的对象。所以,你的怀疑基本上是正确的。

关于c++ - 为什么这个方法调用不像我预期的那样是虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3599695/

相关文章:

c++ - 合法使用 initializer_list 来初始化具有派生类型的对象吗?

c++ - C++ 切片的潜在解决方法?

C++ CRTP派生类对象切片

c++ - 在派生类到基类的转换中 move 语义

c++ - 从文件中读入时如何阻止空格显示为回车?

c++ - 无序映射有错误,提示该函数本身不存在于 C++ 库中

c++ - 策略模式 - C++

c++ - 重载赋值运算符 - 字符指针未正确复制

c++ - 为什么 'pure polymorphism' 比使用 RTTI 更可取?

c++ - 什么是对象切片?