更改对象数组每个元素的属性

问题描述 投票:0回答:2

我有一些概念上的疑问,如果很简单,很抱歉,但我被困住了。

在模拟星系形成过程中,我有一类叫做SolarSystem

class SolarSystem
{
private:
    double sPositionX, sVelocityX, sPositionY;
    double  sVelocityY, sMass, sExcentricity;
public:
//Methods like getPosition(), etc
}

在我的主要功能中,我有对象数组SolarSystem systems[1000]。我需要实现一种算法,使太阳系在银河系中运动(遵循牛顿定律),因此,我必须更改阵列每个成员的属性值,例如位置,速度等(N-身体问题)。

  • 我想我不能创建更改值的方法 algorithm(),因为系统之间存在相互依赖关系,并且该方法无法考虑数组的其他成员。
  • 但是,如果我选择更改function中的属性,需要将这些信息公开,然后,有没有理由类?在主函数positionX[i], mass[i], etc中将属性作为变量int main()会更容易吗?
c++ arrays class object physics
2个回答
0
投票

类使您能够以有意义的方式构造数据,从而提高了可扩展性,可维护性并使代码更易于理解。如果您的主要问题是从类访问systems,则可以将其作为参数传递。在现代C ++中,应使用std::vectorstd::array而不是C样式数组。例如:

class SolarSystem
{
private:
    double sPositionX, sVelocityX, sPositionY;
    double  sVelocityY, sMass, sExcentricity;
public:
    // getters and setters and stuff

    void algorithm(const std::vector<SolarSystem> &otherSystems) {
        for(const auto &otherSystem : otherSystems) {
            // iterate through all systems...
        }
    }
}

如果将太阳能系统也存储在std::vector之类的中,则>]

std::vector<SolarSystem> solarSystems; 

您可以遍历它,并像这样更新所有系统:

for(auto &system : solarSystems) {
    system.algorithm(solarSystems);
}

0
投票

例如,您可以简单地创建另一个名为“ Galaxy”的类,其中包含您的系统。

© www.soinside.com 2019 - 2024. All rights reserved.