如何调用派生类之一
How can i call one of derived classes
我想知道是否可以在函数中使用基类作为参数,但是在调用传递派生类的函数时?
在 .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);
}
输出:
我复制父级
我在福
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- QWidget::p aintEngine:不应再在 QTreeWidget 派生类中调用
- 调用从模板派生的类的静态方法,而不指定模板
- 调用派生类成员函数
- 从基类实例调用派生类方法而不进行强制转换
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 从 c++ 中派生类的析构函数调用虚函数
- 从基类 (C++) 调用派生类中的非虚函数
- 调用不在基类中的派生类函数而不进行动态强制转换,以最大程度地提高性能
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何从 Gtk::窗口调用派生对象的析构函数
- 在dynamic_pointer_cast后调用派生类的构造函数
- 如何使派生类函数在调用时始终调用相同的基类函数?
- C++初始化之前派生类调用基类的方法
- 为什么派生类的实例从基类调用方法?
- 从 Base 引用对象调用派生类的成员
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 基函数中的公共函数,当使用派生对象通过另一个基函数调用时,派生调用基函数