[英]How to use inherited objects in parent class functions?
我有两个类: MovableObject和GravitySource ,它们继承自MovableObject (因为GravitySources也可以移动)。 在MovableObject中,我具有使用GravitySources列表计算运动参数的函数集成 。 因此,我无法将GravitySources列表放入此函数中。 而且我不希望创建GravitySource的MovableObject功能副本(包括集成 )。 那么,如何解决这个问题呢? 它是C ++。
您的MovableObject::integrate
函数声明可以将MovableObject*
指针作为参数,例如:
return_type MovableObject::integrate(Movable* );
这样,您可以将GravitySources
传递给Movable::integrate
,并且行为将是多态的,即您可以通过指向基础MovableObject*
的指针访问virtual
函数。 因此,请确保您具有一些可以通过指向base的指针调用的通用virtual
函数,并将工作委托给它们。
如果要传递GravitySources
数组, GravitySources
棘手一些,因为您不能安全地使用MovableObject*
指针在GravitySources
数组中移动。 但是,您可以做的是向前声明GravitySources
类,然后可以声明
return_type MovableObject::integrate(GravitySources* );
您可以通过指针使用不完整的类型,因此上面的声明是可以的。 只要确保该函数的实现在GravitySources
的完整定义之后GravitySources
。 您现在可以将GravitySources
数组GravitySources
给函数了!
下面是一些玩具示例:
#include <iostream>
class GravitySources; // need this forward declaration
class MovableObject
{
public:
void integrate(GravitySources* gs, std::size_t N); // process N GravitySources
virtual void f(); // our common virtual interface
virtual ~MovableObject() = default;
};
class GravitySources: public MovableObject
{
int _label; // label the instance
public:
GravitySources(int label): _label(label) {}
void f() override;
};
void MovableObject::integrate(GravitySources* gs, std::size_t N)
{
// process the GravitySources
for (std::size_t i = 0; i < N; ++i)
{
gs[i].f();
}
}
void MovableObject::f()
{
std::cout << "MovableObject::f()" << std::endl;
}
void GravitySources::f()
{
std::cout << "GravitySources::f() " << _label << std::endl;
}
int main()
{
MovableObject mo;
GravitySources gs[3] {1, 2, 3}; // 3 GravitySources
mo.integrate(gs, 3); // process them
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.