gpt4 book ai didi

c++ - 一个类的属性仅供外部环境使用是否可以接受?

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:54 26 4
gpt4 key购买 nike

<分区>

有时我们会遇到类不需要使用自己的属性的问题。请参阅方法 A:

struct Ball {
double mass = 1;
double x = 0;
double y = 0;
};

struct World {
std::vector<Ball*> balls;
void run_physics() {
// here we run the physics
// we can access every ball and their x, y properties
}
};

为了避免这种情况,我们可以使用方法B:

struct World;

struct Ball {
World* world = NULL;
double mass = 1;
double x = 0;
double y = 0;
void run_physics() {
if (this->world != NULL) {
// here we run the physics again
// we can access every other ball properties through this->world->balls vector.
}
}
};

struct World {
std::vector<Ball*> balls;
};

但是方法 B 是一个 tight-coupling结构,这意味着 BallWorld 都知道彼此,这是不好的。

那么,哪种方法更好?

  • A:松耦合,但有些类不会使用自己的属性,或者
  • B:类会使用它们的属性,但紧耦合结构?

什么时候使用每一个?

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