将派生类传递给基类参数的函数

Pek*_*kov 4 c++ inheritance pointers reference c++11

我有以下代码:

#include <iostream>

class Base {
  public:
  virtual void sayHello() {
    std::cout << "Hello world, I am Base" << std::endl;
  }
};

class Derived: public Base {
  public:
  void sayHello() {
    std::cout << "Hello world, I am Derived" << std::endl;
  }
};

void testPointer(Base *obj) {
  obj->sayHello();
}

void testReference(Base &obj) {
  obj.sayHello();
}

void testObject(Base obj) {
  obj.sayHello();
}

int main() {
  {
    std::cout << "Testing with pointer argument: ";
    Derived *derived = new Derived;
    testPointer(derived);
  }
  {
    std::cout << "Testing with reference argument: ";
    Derived derived;
    testReference(derived);
  }
  {
    std::cout << "Testing with object argument: ";
    Derived derived;
    testObject(derived);
  }
}
Run Code Online (Sandbox Code Playgroud)

输出为:

Testing with pointer argument: Hello world, I am Derived
Testing with reference argument: Hello world, I am Derived
Testing with object argument: Hello world, I am Base
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么指针大小写void testPointer(Base *obj)和引用大小写都void testReference(Base &obj)返回的派生实例的结果,void sayHello()而不返回按大小写传递的实例的结果?我应该怎样做才能使复制大小写返回派生类函数的结果void sayHello()

Chr*_*nis 6

带有引用或指针的函数引用传入的原始对象,而按值参数将创建对象的副本。由于您只复制基础部分(因为它需要基础对象),因此最终只能使用基础部分的副本,并且由于它基础,因此它的作用类似于基础。

这种“仅基础”复制称为“切片”,因为它仅复制对象的一部分,“切片”派生的部分。