【问题标题】:How to invoke a method an the child class when argument is of type parent class in C++?当参数是 C++ 中的父类类型时,如何调用子类的方法?
【发布时间】:2016-04-26 17:24:18
【问题描述】:

我有以下代码(简化):

#include <cstdio>

class parent
{
public:
  virtual void do_something() const
  {
    printf("hello I'm the parent class\n");
  }
};

class child : public parent 
{
public:
  virtual void do_something() const
  {
    printf("hello I'm the child class\n");
  }
};

void handle(parent p)
{
   p.do_something();
}

int main()
{
  child c;
  handle(c);
  return 0;
}

这会打印hello I'm the parent class,即使我传递了child 类型的参数。如何告诉 C++ 像 Java 一样运行并调用子方法,打印 hello I'm the child class

【问题讨论】:

  • base class 是更常用的术语。

标签: c++ oop inheritance subclass


【解决方案1】:

通过引用(或者,可能是 const 引用)接受参数:

void handle (parent & p)
//        note this ^
{
    p.do_something();
}

在您的情况下,slicing 发生:childparent 部分被提取为 parent 类型的单独对象并转到函数。

如果要将不同的子类放入单个集合中,通常的解决方案是使用智能指针,例如std::unique_ptrstd::shared_ptr

【讨论】:

  • 问题是在“大”代码中我将对象插入vector,但在同一个vector 中可以有不同的子类。我可以将这些引用存储在向量中吗?
  • @msrd0,不,您不能在向量中存储引用。您必须使用 std::unique_ptr 作为向量元素类型,并存储指向动态分配对象的指针。
  • 除了@SergeyA的建议,还可以使用std::reference_wrapper
  • @RSahu,这不太可能成功 - 很难想象所有这些自动对象的生命周期都会超过矢量生命周期......
  • @SergeyA 实际上,我见过这样的用例,但我同意它们很少见。
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
相关资源
最近更新 更多