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

标签 c++ class oop inheritance

我有两个类:MovableObjectGravitySource 继承自 MovableObject(因为 GravitySources 也可以移动)。在 MovableObject 我有函数 integrate 使用 GravitySources 列表计算运动参数。 所以,我无法将 GravitySources 列表放入此函数中。我不想在 GravitySource 中创建 MovableObject 函数(包括 integrate)的拷贝。那么,如何解决这个问题呢?它是 C++。

最佳答案

您的 MovableObject::integrate 函数声明可以将 MovableObject* 指针作为参数,类似于:

return_type MovableObject::integrate(Movable* ); 

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

如果你想传递一个 GravitySources 数组,那就有点棘手了,因为你不能安全地使用 MovableObject* 指针在 中移动GravitySources 数组。不过,您可以做的是转发声明类 GravitySources,然后您可以声明

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

关于c++ - 如何在父类函数中使用继承对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30115016/

相关文章:

c++ - 警告 : flag '0' results in undefined behavior with 's' conversion specifier

javascript - 如何将类分配给 SVG 元素

c++ - 创建指向非静态类成员函数的类成员指针函数变量

java - 动态选择对象

python - 每次在 python 中调用时都会更新 __init__ 中的 self 变量

c++ - 使用动态规划从背包中检索项目

c++ - 在我的项目中添加 mysql.h 是否足够或还需要其他库才能工作

python - 在 Python 中的类之间共享全局变量

c++ - 更新类变量或从成员变量调用类函数会产生运行时错误

c++ - 无法从 char*[] 转换为 char**