如何调用派生类之一

How can i call one of derived classes

本文关键字:派生 调用 何调用      更新时间:2023-10-16

我想知道是否可以在函数中使用基类作为参数,但是在调用传递派生类的函数时?

在 .h 文件中

class parent
{
virtual void foo();
}
class child_a: parent
{
void foo();
}
class child_b: parent
{
void foo();
}

在主要.cpp

void bar(parent p)
{ 
// Doing things
}
int main()
{
child_a a;
bar(a);
return 0;
}

还是我必须使用重载函数? 它有另一种方法可以做到吗?

如果按值传递参数,将调用复制构造器,因此实际上将复制父类型的对象。

如果通过引用或指针传递它,则实际上有一个子类

class parent{
public:   
parent(){
}
parent( const parent &obj){
cout<<"I copy a parent"<<endl;
}
};
class child : public parent{
public:
child(){
}    
child( const child &obj){
cout<<"I copy a child"<<endl;
}
};
void foo(parent p){
cout<<"I am in foo"<<endl;
}
int main()
{
child c;
foo(c);
}

输出:

我复制父级

我在福