gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:34:33 25 4
gpt4 key购买 nike

我有两个类: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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com