当参数在C++中是父类的类型时,如何调用子类的方法?

msr*_*rd0 3 c++ oop inheritance subclass

我有以下代码(简化):

#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;
}
Run Code Online (Sandbox Code Playgroud)

这打印hello I'm the parent class,即使我传递了类型的参数child.我怎样才能告诉C++像Java那样行事并调用子方法,打印hello I'm the child class

lis*_*rus 9

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

void handle (parent & p)
//        note this ^
{
    p.do_something();
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,切片发生:获取的parent部分child作为单独的类型对象提取parent并转到函数.

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

  • @ msrd0,不,你不能在向量中存储引用.你必须使用`std :: unique_ptr`作为向量元素类型,并存储指向动态分配对象的指针. (2认同)
  • 除了@ SergeyA的建议,您还可以使用[`std :: reference_wrapper`](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper). (2认同)