C++ 如何在父类函数中使用继承的对象?

C++ 如何在父类函数中使用继承的对象?,c++,class,oop,inheritance,C++,Class,Oop,Inheritance,我有两个类:MovableObject和GravitySource,它们继承自MovableObject,因为GravitySource也可以移动。在MovableObject,我有一个函数integrate,它使用重力源列表计算运动参数。 所以,我不能把重力源列表放到这个函数中。我不想创建可移动对象函数的副本,包括在GravitySource中集成。那么,如何解决这个问题呢?它是C++。 :您的Mavable Objist::集成函数声明可以将一个Mavable对象*指针作为一个参数,比如:

我有两个类:MovableObject和GravitySource,它们继承自MovableObject,因为GravitySource也可以移动。在MovableObject,我有一个函数integrate,它使用重力源列表计算运动参数。 所以,我不能把重力源列表放到这个函数中。我不想创建可移动对象函数的副本,包括在GravitySource中集成。那么,如何解决这个问题呢?它是C++。

:您的Mavable Objist::集成函数声明可以将一个Mavable对象*指针作为一个参数,比如:

return_type MovableObject::integrate(Movable* ); 
通过这种方式,您可以将GravitySources传递给Movable::integrate,行为将是多态的,即您可以通过指向基本MovableObject*的指针访问虚拟函数。因此,请确保您有一些可以通过指向base的指针调用的公共虚拟函数,并将工作委托给它们

如果您想要传递一个重力源数组,那么它就有点棘手,因为您无法安全地使用MovableObject*指针在重力源数组中移动。但是您可以做的是向前声明类GravitySources,然后您可以声明

return_type MovableObject::integrate(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
}

我想创建StaticGravitySource并在MovableObject中使用它,然后进行多重继承:GravitySource:public StaticGravitySource,MovableObject您对此有何看法?@Robotex我不确定您使用多重继承的目的是什么。为什么不通过指针使用简单的继承和控制呢?我照你说的做了。非常感谢。