Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中,当参数的类型为parent class时,如何调用子类的方法+;?_C++_Oop_Inheritance_Subclass - Fatal编程技术网

C++ 在C+中,当参数的类型为parent class时,如何调用子类的方法+;?

C++ 在C+中,当参数的类型为parent class时,如何调用子类的方法+;?,c++,oop,inheritance,subclass,C++,Oop,Inheritance,Subclass,我有以下代码(简化): #包括 班级家长 { 公众: 虚空do_something()常量 { printf(“你好,我是父类\n”); } }; 类子:公共父类 { 公众: 虚空do_something()常量 { printf(“你好,我是孩子班”\n”); } }; 无效句柄(父级p) { p、 做某事; } int main() { 儿童c; 手柄(c); 返回0; } 这会打印出你好,我是父类,即使我传递了一个类型为child的参数。如何告诉C++像java一样的行为,调用子的方法,

我有以下代码(简化):

#包括
班级家长
{
公众:
虚空do_something()常量
{
printf(“你好,我是父类\n”);
}
};
类子:公共父类
{
公众:
虚空do_something()常量
{
printf(“你好,我是孩子班”\n”);
}
};
无效句柄(父级p)
{
p、 做某事;
}
int main()
{
儿童c;
手柄(c);
返回0;
}

这会打印出
你好,我是父类
,即使我传递了一个类型为
child
的参数。如何告诉C++像java一样的行为,调用子的方法,打印<代码> hello?我是子类< /COD>?< /p> < p>接受引用(或者,也许const引用):< /p> 在您的情况下,会发生这样的情况:
子对象的
父对象
部分被提取为类型为
父对象
的单独对象,并转到函数


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

问题是在“大”代码中,我将对象插入到
向量中,但在同一
向量中可能有不同的子类。我可以在向量中存储这些引用吗?@msrd0,不,你不能在向量中存储引用。你必须使用
std::unique_ptr
作为向量元素类型,并存储指向动态分配对象的指针。除了@SergeyA的建议,你还可以使用@RSahu,这不太可能飞行-很难想象所有这些自动对象的寿命都会超过向量寿命…@SergeyA实际上,我见过这样的用例,但我同意它们很少见。
base
class是更常用的术语。
#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;
}
void handle (parent & p)
//        note this ^
{
    p.do_something();
}