我有一些概念上的疑问,如果很简单,很抱歉,但我被困住了。
在模拟星系形成过程中,我有一类叫做SolarSystem
。
class SolarSystem
{
private:
double sPositionX, sVelocityX, sPositionY;
double sVelocityY, sMass, sExcentricity;
public:
//Methods like getPosition(), etc
}
在我的主要功能中,我有对象数组SolarSystem systems[1000]
。我需要实现一种算法,使太阳系在银河系中运动(遵循牛顿定律),因此,我必须更改阵列每个成员的属性值,例如位置,速度等(N-身体问题)。
algorithm()
,因为系统之间存在相互依赖关系,并且该方法无法考虑数组的其他成员。positionX[i], mass[i], etc
中将属性作为变量int main()
会更容易吗?类使您能够以有意义的方式构造数据,从而提高了可扩展性,可维护性并使代码更易于理解。如果您的主要问题是从类访问systems
,则可以将其作为参数传递。在现代C ++中,应使用std::vector
或std::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);
}
例如,您可以简单地创建另一个名为“ Galaxy”的类,其中包含您的系统。