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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将派生类传递给基类参数的函数相关的知识,希望对你有一定的参考价值。

我有这个代码:

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

输出是:

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

我的问题是为什么指针案例void testPointer(Base *obj)和引用案例void testReference(Base &obj)都返回void sayHello()的派生实例的结果但是没有和复制案例的传递?我该怎么做才能使复制案例返回派生类函数void sayHello()的结果?

以上是关于将派生类传递给基类参数的函数的主要内容,如果未能解决你的问题,请参考以下文章

将派生类引用传递给基类引用

c ++:将指针传递给基类时访问派生类方法?

最佳实践:将派生类的向量传递给基类向量上的方法

虚函数总结

根据条件将不同的派生类分配给基类[重复]

试图将派生类对象地址分配给基类指针向量